I have a list of car objects
List<Car> cars = GetMyListOfCars();
and i want to see if a car is in the list
if (cars.Contains(myCar))
{
}
what does Contains use to figure out if myCar is in the list. Does it do a "ToString()" on my car object. Does it use the Equals() method, the gethashcode()?
I see i can pass in my own IEqualityComparer to force my own implementation but just wanted to understand what it does by default.
It uses Equals()
http://msdn.microsoft.com/en-us/library/bhkz42b3.aspx
Contains
will returntrue
as soon as it can - that is once the first item that fits the criteria is found.A
false
will be returned after all items have been iterated over.In regards to how it does that - it will use reference equality for reference types if you do not override
Equals
.Straight from MSDN - List<T>.Contains:
So in the end it depends on how
T
implements IEquatable.Equals(). For most objects this is going to be a reference comparison, unless overriden. Same location in memory is the same object.