Dictionary.ContainsKey () is not working properly

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 year, month, and date. The goal is to have the data indexed by day. In any case, I implemented the functions Equals () and CompareTo (), as well as the operators == and! =.

Despite this, the Dictionary.ContainsKey () function always returns false, even if the key exists.

I immediately thought that my comparison functions should be broken, but after writing unit tests for all of them, this is not so.

Is there anything about a vocabulary class that I don't know?

+4
source share
2 answers

Using a dictionary, GetHashCode() is crucial. For things that are equal ( Equals() == true ), it should return the same number (but it is allowed to have a collision - i.e. two elements can return the same number by coincidence, but not be considered equal).

Additionally - the hash code should not be changed while the item is in the dictionary. Hashing readonly values ​​is useful for this, but as an alternative: just don't change it! For example, if your equals / hashcode covers the Name and Id objects (say), then do not change these properties of the object or you will never see this record again (even if you pass in the same instance as a key).

+16
source

You only need to override the Equals and GetHashcode functions .
The most common implementation for GetHashcode is the XOR (^) of all members of the instance data.

+2
source

Source: https://habr.com/ru/post/1300270/


All Articles