I am trying to overload the == operator but I am having the following error:
Overloadable unary operator expected
Here is my code
public bool operator == (MyClass nm1)
{
return true;
}
public bool operator != (MyClass m2)
{
return true;
}
I followed the msdn note but still getting the same error
When you overload operator ==
you should do it in a static
method that takes two instances as parameters:
public static bool operator == (MyClass leftSide, MyClass rightSide) {
return true;
}
public static bool operator != (MyClass leftSide, MyClass rightSide) {
return !(leftSide == rightSide);
}
static
context makes the code for your operator feel more "symmetric", in the sense that the code performing the comparison does not belong to a left instance or to the right instance.
In addition, static
makes it impossible to "virtualize" the operator (you could still do it inside the implementation by calling a virtual function, but then you have to do it explicitly).
You need static
, and you need two parameters, not just one.
==
and !=
are always binary operators (two arguments), not unary (one argument).
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