Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / Languages / C#

Using GetHashCode correctly

0.00/5 (No votes)
12 Oct 2011CPOL2 min read 10K  
Assuming you are writing a class (not a struct), you can basically get a fixed random hashcode simply by NOT overriding GetHashCode() but inheriting the implementation from System.Object. Unfortunately the System.Object implementation is not documented in the standard .NET documentation[^] but I...
Assuming you are writing a class (not a struct), you can basically get a fixed random hashcode simply by NOT overriding GetHashCode() but inheriting the implementation from System.Object. Unfortunately the System.Object implementation is not documented in the standard .NET documentation[^] but I know a lot of code relies on it (and that therefore Microsoft is not likely to degrade its performance in the future).

A Stackoverflow answer[^] explains what kind of number you get, but the following description is also allegedly outdated:
"The default implementation returns an index for the object determined by the common language runtime. The index is unique to an instance of an object within an AppDomain for an instance of the executing engine. However, because this index can be reused after the object is reclaimed during garbage collection, it is possible to obtain the same hash code for two different objects. Also, two objects that represent the same value have the same hash code only if they are the exact same object. This implementation is not particularly useful for hashing; therefore, derived classes should override GetHashCode."

I've heard that the System.Object implementation works by making up a random number and putting it either in the sync block (if there is one) or in the object header (if there isn't one). Can anyone verify/clarify?

I read in one place that "By default, System.Object.GetHashCode() uses our object's current location in memory to yield the hash value" -- but this is probably wrong, given that objects can move around in memory at any time thanks to the garbage collector.

The most important property a hash code implementation must have is this[^]: If two objects compare as equal then they must have identical hash codes. Therefore, if you override Equals() then you must also override GetHashCode(), notwithstanding everything else I said :)

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)