From MSDN
Types that implement IComparable must override Equals.Types that override Equals must also override GetHashCode; otherwise, Hashtable might not work correctly.
I didn’t quite get it. Can anyone explain.
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.
IComparable is an interface that defines that two instances of the implementing class can be seen as greater than, less than or equal to one another. Since you have defined equality in the methods of that interface you also need to override the Equals method (and equality operator) to ensure the results from the two are consistent.
In the above example I have implemented IComparable, but not overridden Equals. If you call CompareTo with two separate instances of the class that have the same Value it will say there are equal. If you call Equals with the same two instances it will say they are not equal as it will test to see if they are the same object (the default implementation of Equals).
Two equal items should return the same hash code (which are used for quickly finding items used as keys in hash tables) so if you override Equals then you should also override GetHashCode()
As an example I just created the following class in my IDE:
And ran Resharper’s helpful “Generate Equality” function saying that I wanted both A and B to affect equality. This is the code it created:
So if you are overriding Equals then you should also define all of the above to ensure consistency, if you are implementing IComparable then the same applies.