Mahith Amancherla
Mahith Amancherla

Reputation: 73

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

Upvotes: 4

Views: 5322

Answers (3)

Simon_Weaver
Simon_Weaver

Reputation: 146180

If you want to use IEquatable<T> you can do so without having to create a separate class but you do need to implement GetHashCode().

It will pair up GetHashCode() and bool Equals(T other) and you don't have to use the archaic Equals signature.

// tested with Dictionary<T>
public class Animal : IEquatable<Animal>
{
    public override int GetHashCode()
    {
        return (species + breed).GetHashCode();
    }

    public bool Equals(Animal other)
    {
        return other != null &&
               (
                  this.species == other.species &&
                  this.breed == other.breed &&
                  this.color == other.color                   
               );
    }
}

Upvotes: -1

Lucas Trzesniewski
Lucas Trzesniewski

Reputation: 51430

It will use IEqualityComparer<T>.Default if you don't specify any equality comparer explicitly.

This default equality comparer will use the methods Equals and GetHashCode of your class.

Your key class should not implement IEqualityComparer, this interface should be implemented when you want to delegate equality comparisons to a different class. When you want the class itself to handle equality comparisons, just override Equals and GetHashCode (you can also implement IEquatable<T> but this is not strictly required).

Upvotes: 2

Servy
Servy

Reputation: 203821

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.

Upvotes: 6

Related Questions