[Mono-dev] Possible bug in Dictionary

Gustavo Guerra gmcg at acm.org
Sat Oct 22 08:25:22 EDT 2005


Hi

In the documentation is stated that the default constructor of 
Dictionary<TKey, TValue> will use EqualityComparer.Default, that will use 
the IEquatable interface if TKey implements it. That is not the case. If we 
set a breakpoint in the IEquatable<TKey>.Equals, it isn't called, and the 
Dictionary class seems to be basing its results on GetHashCode of TKey 
instances. This program:

public class A : IEquatable<A>
{
    private int _i;
    public A(int i) { _i = i; }
    bool IEquatable<A>.Equals(A other) { return _i.Equals(other._i); }

    public static void Main()
    {
        if (!EqualityComparer<A>.Default.Equals(new A(2), new A(2)))
            Console.WriteLine("BUG 1");
        Dictionary<A, int> d = new Dictionary<A, int>();
            A a = new A(2);
        d.Add(a, 3);
        int value;
        if (!d.TryGetValue(new A(2), out value))
            Console.WriteLine("BUG 2");
        if (!d.TryGetValue(a, out value))
            Console.WriteLine("BUG 3");
        d = new Dictionary<A, int>(new EqualityComparer<A>.Default);
        d.Add(a, 3);
        if (!d.TryGetValue(new A(2), out value))
            Console.WriteLine("BUG 4");
    }
}

Will print:
BUG2
BUG4

When it shouldn't print anything.
The problem seems to be not in EqualityComparer<>.Default but in Dictionary 
that doesn't use it.

Best regards,
Gustavo Guerra






More information about the Mono-devel-list mailing list