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 !=?

Jonathan Wood
  • 65,341
  • 71
  • 269
  • 466
  • 4
    Quick terminology correction: you don't *override* operators - you *overload* them. – Jon Skeet Jul 25 '11 at 21:59
  • 1
    When you override `Equals`, you need to override `GetHashCode` as well, as it will check equality based on a hash function. – Igoris Azanovas Jul 25 '11 at 22:00
  • @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. – Suncat2000 Feb 02 '17 at 13:45

2 Answers2

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 :-)

Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928
  • Okay, so can anyone point to a good algorithm that takes converts an integer value to a reasonable hash value? – Jonathan Wood Jul 25 '11 at 22:30
  • 1
    @Darin why do we need to override object.equals() when we just overload "==" operator? – Sandeep Jul 26 '11 at 16:53
  • @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... – porges Aug 03 '11 at 10:51
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.

Grant Thomas
  • 44,454
  • 10
  • 85
  • 129