1

Why does this simple test fail?

 var dict1 = new Dictionary<int, int> {{1, 15}};
 var dict2 = new Dictionary<int, int> {{1, 15}};

 var equals = EqualityComparer<IDictionary<int, int>>.Default.Equals(dict1, dict2);

 Assert.IsTrue(equals);

...thank you very much. I ended up with my own dictionary... Does this look like something one would and should do?

public class EquatableDictionary<TKey, TValue> : Dictionary<TKey, TValue>, IEquatable<EquatableDictionary<TKey, TValue>>
{
    public EquatableDictionary() { }

    protected EquatableDictionary(SerializationInfo info, StreamingContext context) : base(info, context)
    {
    }

    public bool Equals(EquatableDictionary<TKey, TValue> other)
    {
        if (other == null)
            return false;

        foreach (var kvp in this)
        {
            if (!other.TryGetValue(kvp.Key, out var otherValue))
                return false;

            if (!Equals(kvp.Value, otherValue))
                return false;
        }

        return true;
    }
}
Wolfgang
  • 2,188
  • 1
  • 25
  • 24

1 Answers1

4

As it is mentioned in documentation:

The Default property checks whether type T implements the System.IEquatable<T> interface and, if so, returns an EqualityComparer<T> that uses that implementation. Otherwise, it returns an EqualityComparer<T> that uses the overrides of Object.Equals and Object.GetHashCode provided by T.

Since IDictionary<TKey,TValue> does not implement System.IEquatable<IDictionary<TKey,TValue>> , an equality comparer would be returned that uses the overrides of Object.Equals and Object.GetHashCode provided by T. Since both methods are not overriden in your case, the default implementation would be returned, which has as a result two dictionaries even if the have all the keys to be the same and all the corresponding values to be the same, the dictionaries containing them to not be equal.

Christos
  • 53,228
  • 8
  • 76
  • 108