Reputation: 20378
I have a dictionary.
Dictionary<YMD, object> cache = new Dictionary<YMD, object>();
The YMD class is one of my inventions, it is a class containing only the year, month, and date. The purpose is that the data will be indexed by the day is relates to. Anyhow, I have implemented the Equals() and CompareTo() functions, as well as the == and != operators.
Despite this, the Dictionary.ContainsKey() function will always return false, even if the key exists.
I immediately thought my comparison functions must be broken, but after writing unit tests for all of them it does not appear to be the case.
Is there something about the dictionary class that I do not know?
Upvotes: 4
Views: 7195
Reputation:
You need only to override the Equals and GetHashcode functions.
The most common implementation for GetHashcode is to XOR (^) all of the instance's data members.
Upvotes: 2
Reputation: 1062550
With a dictionary, GetHashCode()
is critical. For things that are equal (Equals() == true
) it must return the same number (but it is permitted to have collisions - i.e. two items can return the same number by coincidence but not be considered equals).
Additionally - the hash-code must not change while the item is in the dictionary. Hashing on readonly
values are good for this, but alternatively: just don't change it! For example, if your equals / hashcode spans an entities Name
and Id
(say), then don't change those properties of the object, or you may never see that record again (even if you pass in the same instance as the key).
Upvotes: 16