Code Inspection: Non-readonly type member referenced in 'GetHashCode()'
MSDN documentation of the
GetHashCode() method does not explicitly require that your override of this method returns a value that never changes during the object's lifetime. Specifically, it says:
On the other hand, it says that the hash code should not change at least when your object is in a collection:You can override GetHashCode for immutable reference types. 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.
But why do you need to override
GetHashCode() in the first place? Normally, you will do it if your object is going to be used in a
Hashtable, as a key in a dictionary, etc., and it's quite hard to predict when your object will be added to a collection and how long it will be kept there.
With all that said, if you want to be on the safe side make sure that your override of
GetHashCode() returns the same value during the object's lifetime. JetBrains Rider will help you here by pointing at each non-readonly field or non-get-only property in your implementation of
GetHashCode(). If possible, JetBrains Rider will also suggest quick-fixes to make these members read-only/get-only.