When should we override the GetHashCode() method provided by ‘Object‘ class in ‘System‘ namespace?
Share
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
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.Equalsjust looks at the UTF-16 code points which make up the string, and compares them in the simplest conceivable fashion.)