1

I am getting the same hash code before and after I update this dictionary.

I am printing the hash code using:

MessageBox.Show(dict.GetHashCode().ToString());

Can anyone please help me on this?

0

3 Answers 3

4

This is by design. To quote the documentation:

A hash code is a numeric value that is used to insert and identify an object in a hash-based collection [...]

Thus, should your dict itself ever be contained in some dictionary, it is vital that its hash code does not change, even if its content changes. The documentation is clear on that as well:

In general, for mutable reference types, you should override GetHashCode only if:

  • You can compute the hash code from fields that are not mutable; or
  • You can ensure that the hash code of a mutable object does not change while the object is contained in a collection that relies on its hash code.

Otherwise, you might think that the mutable object is lost in the hash table. [...]

Sign up to request clarification or add additional context in comments.

Comments

1

You would have to inherit Dictionary<K,V>, override GetHashCode() and implement it reasonably. The default implementation just doesn't do that.

Also remember you would have to override and implement Equals() as well.

Comments

0

The Equals(Object) method for Dictionary doesn't test whether two references refer to dictionaries with equal contents, but instead tests whether references refer to the same dictionary. If some particular dictionary is the 592nd object created since program startup, then its Equals method will test whether the passed-in reference identifies the 592nd object created since program startup. Adding or removing items from the dictionary will not affect the set of references that the Dictionary considers equal to itself (it will regard as equal all references that identifies the 592nd object, and as unequal all reference that don't) and as such, shouldn't affect the hash code either.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.