.NET - how does IndexOf work if I don't implement IComparable in my class?
I have a collection of custom object, and I am doing IndexOf 开发者_JAVA技巧to find the index of a specific object. I would assume that the IndexOf would use IComparable implementation to check to see if the objects match, but I am not implementing it in my class.
How does IndexOf determine that two objects are equal?
Thanks!
It's not clear which type you're calling IndexOf
on anyway, but most collections won't use IComparable
anyway - they'll just use Equals
and do a linear search. Unless you've overridden Equals
(or implemented IEquatable<T>
), a class will be compared by reference identity, and a struct will have auto-generated equality comparisons. IComparable
would be used for something like a binary search of a sorted list.
From MSDN for the List(T).IndexOf Method:
This method determines equality using the default equality comparer EqualityComparer(T).Default for T, the type of values in the list.
The comparison is done using EqualityComparer<T>.Default
.
EqualityComparer<T>.Default
will return a default implementation if one exists...otherwise it uses an implementation based on Object.Equals()
which I'm guessing is what is being used in your case.
Unless you've either overriden Equals()
or implemented IEquatable<T>
, Object.Equals()
will check for reference equality only.
精彩评论