ICollection<T>.Contains on custom types

.net, c#, collections, contains

Solution

Because your type doesn't override Equals, the default implementation of Equals will be used, i.e. reference equality. So Contains will be true if the collection contains that very instance.

To use your own comparison, implement `IEqualityComparer<T>` (e.g. to compare the Ids) and pass an instance of your comparer into the Contains method. (This assumes you are able to use LINQ extensions, as the "native" `ICollection<T>.Contains` method doesn't have the IEqualityComparer overload.)

Problem

If I have a (reference - does it matter?) type MyType which does not override the Equals method, what heuristics will be used when determining if an ICollection<MyType> contains a given instance of the type? What's the best way to use my own heuristics (e.g. check for the equality of the Id property value)?

Original source