views:

163

answers:

3

I have a collection of custom object, and I am doing IndexOf 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!

+1  A: 

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.

Ahmad Mageed
+5  A: 

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.

Jon Skeet
+1  A: 

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.

Justin Niessner