DevRuss123
DevRuss123

Reputation:

Dictionary(TKey, TValue) GetHashCode and Equals - How do they work?

You would think that if two dictionaries contained the same keys and values they would return the same hash code and be equal right? but they don't - what am i doing wrong? or how do I compare dictionaries in this way?

Thanks. Code sameple below

/In this case I also want to test the order is the same/equal.

     SortedDictionary<int,string> sd1 = new SortedDictionary<int,string>();
        sd1.Add(1,"one");
        sd1.Add(2, "two");
        sd1.Add(5, "five");
        int sd1Hash = sd1.GetHashCode();

        SortedDictionary<int, string> sd2 = new SortedDictionary<int, string>();
        sd2.Add(1, "one");
        sd2.Add(2, "two");
        sd2.Add(5, "five");
        int sd2Hash = sd2.GetHashCode();

        //This is false
        bool areEqual = sd1.Equals(sd2);

Upvotes: 1

Views: 727

Answers (3)

0100110010101
0100110010101

Reputation: 6729

You can check out MSDN for this issue:

The default implementation of Equals supports reference equality for reference types, and bitwise equality for value types. Reference equality means the object references that are compared refer to the same object. Bitwise equality means the objects that are compared have the same binary representation.

So, since the SortedDictionary contains references, they will be compared. and those are obviously different.

You can find more info on: http://msdn.microsoft.com/en-us/library/bsc2ak47.aspx

Upvotes: 0

LukeH
LukeH

Reputation: 269398

If you want to test that the collections are equal, including their ordering:

bool areEqual = sd1.SequenceEqual(sd2);

If you wanted to treat the collections as unordered sets:

bool areEqual =
    (sd1.Count == sd2.Count) && (sd1.Intersect(sd2).Count() == sd1.Count);

(SequenceEqual and Intersect can also take an IEqualityComparer parameter, if required.)

As several other answers have stated, SortedDictionary doesn't override the default implementations of Equals or GetHashCode. The default implementation of Equals will use reference equality and return false because you're comparing two separate objects.

Upvotes: 4

Thomas Levesque
Thomas Levesque

Reputation: 292465

You would think that if two dictionaries contained the same keys and values they would return the same hash code and be equal right?

No, this is not how the Equals and GetHashcode methods are implemented. They are not overriden, so the is the default System.Object implementation, which just compares references.

Upvotes: 0

Related Questions