Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Which IEqualityComparer is used in a Dictionary?

Lets say I instantiate a dictionary like this

var dictionary  = new Dictionary<MyClass, SomeValue>();

And MyClass is my own class that implements an IEqualityComparer<>.

Now, when I do operations on the dictionary - such as Add, Contains, TryGetValue etc - does dictionary use the default EqualityComparer<T>.Default since I never passed one into the constructor or does it use the IEqualityComparer that MyClass implements?

Thanks

like image 911
Mahith Amancherla Avatar asked Oct 28 '25 10:10

Mahith Amancherla


1 Answers

It will use the default equality comparer.

If an object is capable of comparing itself for equality with other objects then it should implement IEquatable, not IEqualityComparer. If a type implements IEquatable then that will be used as the implementation of EqualityCOmparer.Default, followed by the object.Equals and object.GetHashCode methods otherwise.

An IEqualityComparer is designed to compare other objects for equality, not itself.

like image 106
Servy Avatar answered Oct 31 '25 01:10

Servy