Reputation: 1706
I am writing a facade for IList<T>
to implement change tracking. Does Clear
use RemoveAt
or Remove
or something else entirely? I need to know if I need to set all the items tracking state inside of Clear
or if changing the tracking state only in Remove
, and RemoveAt
will be enough.
Similarly, does Add
use Insert
? Does Remove
or RemoveAt
use each other?
Any other input into such an implementation is also welcome.
Edit: Do extension methods for List use pre-existing methods or is it new code? I don't know if I need to implement those as well.
Upvotes: 0
Views: 383
Reputation: 241641
Does
Clear
useRemoveAt
orRemove
or something else entirely?
You can not rely on implementations of IList.Clear
to use IList.RemoveAt
or IList.Remove
. It is up to the specific implementation to do whatever it wants.
Note that you can't even really rely on Clear
actually removing all items from the instance. An interface does not enforce behavior, it is not actually a contract.
There's a huge misconception on what interfaces actually are. You'll hear people say that "interfaces are contracts". They are not. They merely specify that there will be some methods with certain signatures and return types that you will be able to invoke if you have an object that implements a given interface. That's it. There is no guarantee whatsoever on the implementation, or the behavior.
Additionally, relying on implementation details is a gigantic code smell. They could change on you at any moment without you knowing causing your code to fail and die miserably. Do not rely on implementation details.
Similarly, does Add use Insert?
Similarly, you can not rely on IList.Add
using IList.Insert
.
Does
Remove
orRemoveAt
use each other?
You can not rely on it being true.
Upvotes: 6
Reputation: 2415
It doesn't matter if you write a facade since these methods are not virtual. Event if implementation of Clear called Remove (it doesn't) it wouldn't be your overriden Remove.
So that makes your life easier. You are free to implement this tracking fully in your wrapper.
Upvotes: 3
Reputation: 108957
From source, List<T>
uses Array.Clear()
// Clears the contents of List.
public void Clear() {
if (_size > 0)
{
Array.Clear(_items, 0, _size); // Don't need to doc this but we clear the elements so that the gc can reclaim the references.
_size = 0;
}
_version++;
}
Upvotes: 2
Reputation: 62027
IList
is simply a contract. What a class implementing IList
does behind the scenes is its own business and it doesn't have to make any promises. Some implementors might iterate through their items and call Remove
against them, while others might just delete their backing store and create a new one, or many other possibilities.
It's probably not a good idea to assume someone implementing an interface implements it in a certain way. This is certain to break in unexpected ways at some point.
Upvotes: 2