Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When to override GetHashCode()?

Tags:

c#

.net

When should we override the GetHashCode() method provided by 'Object' class in 'System' namespace?

like image 678
tush1r Avatar asked Apr 09 '09 05:04

tush1r


1 Answers

When you override Equals, basically. When you want to provide a different idea of equality than simple reference equality.

String is a good example of this - two strings are equal (under a simple Equals call) if they represent the same sequence of characters. The hash code reflects this, such that if two strings are equal they will have the same hash code. (The reverse isn't necessarily true - two unequal strings can have the same hash code, but it's unlikely.)

(Strings are tricky in other ways, mind you - there are lots of different ideas of equality based on culture and casing, but String.Equals just looks at the UTF-16 code points which make up the string, and compares them in the simplest conceivable fashion.)

like image 193
Jon Skeet Avatar answered Oct 07 '22 10:10

Jon Skeet