The more I read the more confused I am from blogs, to MSDN, to other stackoverflow questions and responses.
This article: https://msdn.microsoft.com/en-us/library/ms173147%28VS.90%29.aspx States: "The new implementation of Equals should not throw exceptions. It is recommended that any class that overrides Equals also override Object.GetHashCode"
But this article: http://www.aaronstannard.com/overriding-equality-in-dotnet/ States: "An important caveat - you should only override GetHashCode if your objects are immutable."
1) So, do I listen to the first article straight from Microsoft? Or do I listen to the second article who seems to have a much stronger hashcode return than Microsoft.
2) If using the Microsoft example, the example returns the instance members int values using exclusive-OR. Is this something I do with all value types? How come there is an option on the int32 struct to return the hashcode then? When do I return the hashcode vs the value?
3) When do I use the more complex hashcode return (from the second article) vs the more simple from the first (Microsoft) article
4)If the object is immutable and cannot be changed, and two immutable objects of the same type are Equal by value, then why would the HashCode matter?
To my mind, you should always override GetHashCode
if you override Equals
- otherwise you're violating the contracts of those methods.
However, for mutable types, client code needs to be aware that if it does mutate a value used as a key in a Dictionary
or an entry in a HashSet
, in a way that affects equality (and thus probably the hash code), they may well end up not being able to find it again. That's specified in the Dictionary<,>
documentation, for example:
As long as an object is used as a key in the
Dictionary<TKey, TValue>
, it must not change in any way that affects its hash value.
Basically, it's up to the client to use the type properly - just as it's up to the client to dispose of IDisposable
instances, not to use types which aren't designed to be thread-safe from multiple threads without synchronization etc.
See more on this question at Stackoverflow