Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ICollection<T>.Contains on custom types

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)?

like image 501
Ben Aston Avatar asked Jan 27 '10 00:01

Ben Aston


2 Answers

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.)

like image 102
itowlson Avatar answered Nov 05 '22 16:11

itowlson


It's not defined by ICollection<T>- different implementations can use different methods. From MSDN:

Implementations can vary in how they determine equality of objects; for example, List<T> uses Comparer<T>.Default, whereas Dictionary<TKey, TValue> allows the user to specify the IComparer<T> implementation to use for comparing keys

In most cases it will just compare the references, but you should check the documentation for the specific ICollection<T> you are using.

like image 43
Mark Byers Avatar answered Nov 05 '22 16:11

Mark Byers