I read most questions on StackOverflow with regards to GetHashCode
. But I am still not sure whether I have to override GetHashCode
on reference types. I picked up the following from someones answer in another question:
Object.GetHashCode() uses an internal field in the System.Object class to generate the hash value. Each object created is assigned a unique object key, stored as an integer,when it is created. These keys start at 1 and increment every time a new object of any type gets created.
If this is still true in .NET Framework 3.5 (can someone please confirm?), then the only problem I see with the default implementations of reference types is that the hash code will have a poor distribution.
I'll break up my questions:
a) So it it recommended to override GetHashCode
too if it is used in a Dictionary
or does the default implementation perform just fine?
b) I have reference types where it would be easy to do since they have fields that identify them uniquely but what about those reference types where all members are also reference types. What should I do there?
You only need to override GetHashCode() on reference types if you override Object.Equals().
The reason for this is simple - normally, 2 references will always be distinct (a.Equals(b)==false, unless they're the same object). The default implementation of GetHashCode() will provide 2 distinct hashes in this case, so all is good.
If you override Equals(), though, this behavior is not guaranteed. If two objects are equal (as per Equals()), you need to guarantee that they'll have the same hash code with GetHashCode, so you should override it.