I was messing around with a List<T> object today and found that IndexOf() never calls T's int IComparable<T>.CompareTo(T t) method. I used to do this with arrays of container objects all of the time in v1.x and it worked like a champ. Is it broken in beta 2?
EDIT: OK... it calls it for BinarySearch(), but it gives up before getting to the end of the collection. That's still weird!
4 Comments
Why should it call CompareTo?
It can make an equality text (==). Note that IndexOf imho does not search for a similar object, but to THE OBJECT. Runnind along in a loop and checking for equality satisfies this.
Doesn't IndexOf simply traverse the list and call Equals? It does that in .NET 1.x
But that's not what the docs say...
"This method determines equality using the default comparer System.Collections.Generic.Comparer<>.Default. System.Collections.Generic.Comparer<>.Default checks whether type T implements System.IComparable<> and uses that implementation, if available. If not, System.Collections.Generic.Comparer<>.Default checks whether type T implements System.IComparable. If type T does not implement either interface, this method uses System.Object.Equals."
So by that definition, if T implements IComparable<> (and in my case it does), then that method from the interface should determine equality.
It calls BinarySearch... which by definition doesn't search an entire collection. BinarySearch would search a sorted Binary Tree. I guess we now know that List<> is actually a Binary Tree, not a linked list.