Suppose there is an object with an overridden GetHashCode , which I want to make a key. GetHashCode calculated as the collection of the GetHashCode of all fields.

I understand correctly that HashCode is calculated only 1 time when added to the dictionary?

Those. if during the life of a dictionary object, one of the key fields changes, then when you add a new object to the dictionary with the same fields, it will not notice duplicates?

Judging by the source code it is.

It turns out that for such cases you need to do your vocabulary implementation or is there something ready that HashCode recounts on the go?

1 answer 1

The object hashcode should not change over the life of the object. This recommendation becomes a strict rule if the object serves as a key in a Dictionary<K, V> or lies in a HashSet<T> .

The fact is that when searching for an object in the Dictionary , the hashcode is first checked, and on its basis the group in which further search takes place is determined. If the hashcode changes, the object may not be found.

It makes sense either to read the hashcode only by immutable fields, or to fix the hashcode and memorize it in the field of the object. Well, or just to guarantee in the code that while the object is in the dictionary, its hashcode does not change.

Good additional reading on the topic: Eric Lippert , Rules and guidelines for overriding GetHashCode . And more: MSDN: Remarks on Object.GetHashCode Method (especially the “Notes to Inheritors” section).


Tricks with a dynamic conversion of hashcode will not work, because in the dictionary an object falls into one or another cell (bucket) of a hash table depending on its hashcode. If you allow a hashcode change, then the table will have to be rebuilt (recompute the key cells) each time it is accessed, which means a catastrophic performance drop.