Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dictionary.ContainsKey() not working as expected

Tags:

c#

.net

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?

like image 425
Nippysaurus Avatar asked Dec 02 '22 06:12

Nippysaurus


1 Answers

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).

like image 73
Marc Gravell Avatar answered Dec 25 '22 05:12

Marc Gravell