When should we override the GetHashCode() method provided by 'Object' class in 'System' namespace?
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.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With