Search code examples
c#dictionaryiequalitycomparer

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


Solution

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