Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Operator overloading ==

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

like image 636
Kasparov92 Avatar asked Dec 11 '22 17:12

Kasparov92


2 Answers

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

like image 52
Sergey Kalinichenko Avatar answered Dec 31 '22 23:12

Sergey Kalinichenko


You need static, and you need two parameters, not just one.

== and != are always binary operators (two arguments), not unary (one argument).

like image 40
Jeppe Stig Nielsen Avatar answered Dec 31 '22 23:12

Jeppe Stig Nielsen