If your classes don't have too many mutators, you can cache the hash code and just return the cached value from GetHashCode()
. (Even if you have a lot of mutators you can do this, but it is likely to be much less effective if objects are frequently mutated.)
You should lazily evaluate it. You will need to know when it is dirty and needs to be recalculated. You can do this easily by adding a bool isHashCodeDirty
field, which is initialised to true when the class is constructed and also by every mutator method.
Then in your implementation of GetHashCode()
if isHashCodeDirty
is true, set it to false and recalculate and return the hash code. If it's false, just return the cached value.
You have to be careful with multithreading here, of course. I think that adding a lock to GetHashCode() would impact performance quite a lot though!
The ideal of course is to have immutable classes; then you just calculate the hash code once in the constructor and it'll never change thereafter.