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 !=
?
In a class, if you overload the Equals method, you should overload the == and != operators, but it is not required. This code reports that p1 equals p2 despite the difference in z values. The difference is ignored because the compiler picks the TwoDPoint implementation of IEquatable based on the compile-time type.
When a binary operator is overloaded the corresponding assignment operator, if any, must be explicitly overloaded. We can use the default equality operator in an overloaded implementation of the equality operator. A public or nested public reference type does not overload the equality operator.
A user-defined type can overload a predefined C# operator. That is, a type can provide the custom implementation of an operation in case one or both of the operands are of that type. The Overloadable operators section shows which C# operators can be overloaded. Use the operator keyword to declare an operator.
The equality operators, equal to ( == ) and not equal to ( != ), have lower precedence than the relational operators, but they behave similarly. The result type for these operators is bool . The equal-to operator ( == ) returns true if both operands have the same value; otherwise, it returns false .
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 :-)
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