Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Overriding Equality Operators

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

like image 856
Jonathan Wood Avatar asked Jul 25 '11 21:07

Jonathan Wood


People also ask

Should I override equality and inequality operators?

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.

What is the correct way to overload an equality operator?

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.

Can you override operators in C#?

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.

What is an equality 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 .


1 Answers

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

like image 75
Darin Dimitrov Avatar answered Sep 22 '22 21:09

Darin Dimitrov