Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does Dictionary.Equals() have an implementation?

I have a Dictionary which I am comparing to another Dictionary (variables typed as IDictionary). Doing d1.Equals(d2) yields false. Writing my own code below yields true. Both are System.Collections.Generic.Dictionary. Am I missing something or does Dictionary not have an Equals implementation that compares keys/values?

private static bool DictEquals<K, V>(IDictionary<K, V> d1, IDictionary<K, V> d2)
{
    if (d1.Count != d2.Count)
        return false;

    foreach (KeyValuePair<K, V> pair in d1)
    {
        if (!d2.ContainsKey(pair.Key))
            return false;

        if (!Equals(d2[pair.Key], pair.Value))
            return false;
    }

    return true;
}
like image 661
Mike Q Avatar asked Oct 30 '09 13:10

Mike Q


4 Answers

Dictionary.Equals() uses the default Equals from Object, checking if the two objects are the same reference, as does all the other default collections. You're free to create your own subclass with value semantics, though that usually includes things being immutable as well.

like image 101
SoftMemes Avatar answered Nov 04 '22 02:11

SoftMemes


Probably the Equals method of the Dictionary class simply resorts to the default implementation inherited from Object, that is, it just compares the Dictionary object reference passed with its own reference. See here: Object.Equals reference

like image 36
Konamiman Avatar answered Nov 04 '22 03:11

Konamiman


Assuming that two dictionaries, one being a SortedList<TKey, TValue> and one a Dictionary<TKey, TValue>, are compared for equality, should it really return true if the items are the same? That would be pretty bad, since they have different characteristics and features (the SortedList<,> for instance allows retrieval via index).

Also, equality and hash code are logically tied together. The hash code should be immutable, otherwise all hash based algorithms will not work. You cannot guarantee this when you're using the contents to check for equality. Therefore, the default implementation (checking if they are the same instance) is quite sane. You're free to create your own content equality comparison though.

like image 2
Lucero Avatar answered Nov 04 '22 03:11

Lucero


Others have mentioned that it is using the Object.Equals implementation, you can use the following to override it:

public class EqualsDictionary<T, T> : Dictionary<T, T>
{
    public override bool Equals(object obj)
    {
        //Place your comparison implementation here
    }
}
like image 1
Yuriy Faktorovich Avatar answered Nov 04 '22 01:11

Yuriy Faktorovich