Overriding Equality Operators
Asked Answered
T

2

8

I've implemented a class that overloads the == and != operators.

This seems to work fine; however, I get the warning 'type' defines operator == or operator != but does not override Object.Equals(object o).

Okay, so I implemented Equals. But now I get the warning 'type' defines operator == or operator != but does not override Object.GetHashCode().

Does this end at some point? Or have I wandered into a never-ending trail of requirements just because I want to overload == and !=?

Tungting answered 25/7, 2011 at 21:56 Comment(3)
Quick terminology correction: you don't override operators - you overload them.Siphon
When you override Equals, you need to override GetHashCode as well, as it will check equality based on a hash function.Plaster
@IgorisAzanovas No, Equals will not check equality based on a hash function (unless you overload it and specifically code it that way). The hash function is there for supporting hashed collections and is not expected to generate a unique value, only one that ideally will be infrequently used.Transvestite
R
11

Does this end at some point?

Yes, once you implement GetHashCode it will end. Eric Lippert has blogged about its importance. All I can do is suggest you to read and trust him :-)

Riegel answered 25/7, 2011 at 21:57 Comment(3)
Okay, so can anyone point to a good algorithm that takes converts an integer value to a reasonable hash value?Tungting
@Darin why do we need to override object.equals() when we just overload "==" operator?Wellborn
@Jonathon: if your only identifying information is an int, the built-in int type uses itself as its hash value. If it's good enough for them...Mayapple
B
1

Yes, it will end when you override GetHashCode.

When implementing equality operators, and furthermore Equals, it is the responsibility of the programmer to provide an implementation to deliver a custom hash code for that type.

See this MSDN reference for details.

Bratislava answered 25/7, 2011 at 21:58 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.