Non-readonly fields referenced in GetHashCode()

If you change the value of a field, used in the hash calculation, after the object had been added to a hash based container like Dictionary or HashSet, you are essentially breaking the inner state of the container. Why is that? Because the object had been stored in a bucket corresponding to a hash value based on its initial state. When the state is changed, e.g. 'age' is modified, the object will continue to live in its old bucket in the hash container although this is not the correct bucket based on its current hash code. This can lead to pretty messy behaviour and a lot of headaches. I've written an article on this topic with some very specific examples, so you may want to check it out.


To summarise what was discussed in the comments:

Hashing is designed to provide a value that doesn't change for a given object, no matter what happens to it - hence it's best to depend only on readonly fields in your GetHashCode method.

Firstly, I would suggest making the name and lname field readonly, because they probably don't change in your usage scenario.

As for age, this is something that changes regularly, so probably best to store a DateTime for date of birth, which never changes. Then you can make that readonly too.

Tags:

C#

.Net

.Net 4.0