Algorithms for overridden System.Object.GetHashCode

In .NET System.Object.GetHashCode method is use in a lot of places throughout the .NET base class libraries. Especially when finding items in a collection fast or to determine equality. Is there a standard algorithm/ best practise on how to implement the GetHashCode override for my custom classes so I don’t degrade performance?

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.


Leave a Reply

Your email address will not be published. Required fields are marked *