Question

I've read that an object's hashcode should not change while it is part of a Dictionary. Because if it changed, there would be no way to find it in the Dictionary.

Why doesn't the Dictionary class have logic to move an object to the correct bucket when it detects that the object's hashcode has changed?

Was it helpful?

Solution

Why doesn't the Dictionary class have logic to move an object to the correct bucket when it detects that the object's hashcode has changed?

Just to be sure, we are talking about the hash of the key here, the hash of the value is irrelevant.

The important part of your comment is: [...] when it detects that the object's hashcode has changed. ...but how?

  • Continuously iterating over all entries in the dictionary would be both inefficient and not thread safe.
  • The other option would that for each possible key, you should add a a listener's mechanism to trigger an event when the key's value/hashcode changes. That would really be a PITA and inefficient too.

Since it's pretty rare that you have to modify keys within your dictionary, it's by far easier and more efficient to remove the entry with the old key and add it back with the new key.

OTHER TIPS

Short answer: Dictionary can't detect that some hashcode changed. There is no event that it can subscribe to. Getting hashcode is just a call to Object.GetHashCode(). That method is called once when you insert the object. For obvious performance reasons Dictionary can't call that method for all the objects in a collection every time you perform some operation on Dictionary.

Why doesn't the Dictionary class have logic to move an object to the correct bucket when it detects that the object's hashcode has changed?

Because that defeats the object of a dictionary. The whole of a dictionary is to have an immutable set of keys. Since the key is immutable, its hash value won't change. If your hash values are changing, then that means your keys aren't immutable and a dictionary isn't the right type for you. Take a look at the KeyedCollection<TKey, TItem> class, which is an abstract collection class that lets you override some of the dictionary behaviours under the hood to create hash tables with mutable keys for example. It's obviously slower, but may well suit your needs.

If the hash code of the key can change, then the keys can change, and keys that were different can become equal. And now you have a dictionary with equal values and a serious problem.

Licensed under: CC-BY-SA with attribution
scroll top