简体   繁体   中英

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

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

As you can see in the MSDN tutorial these are binary operators and thus they need two arguments. The operators should also be static as they will be part of the class and not the instance. See this & this .

public static bool operator == (MyClass nm1, MyClass mn2)
{
   return true;
}

public static bool operator != (MyClass m1, MyClass m2)
{
   return true;
}

the correct signature is:

public static bool operator ==(MyClass nm1, MyClass other)
{

}

public static bool operator !=(MyClass nm1, MyClass other)
{

}

The second parameter doesn't necessarily have to be of type MyClass though - but at least one of them must be.

  public static bool operator == (MyClass m1, MyClass m2)
  {
       return true;
  }

  public static bool operator != (MyClass m1, MyClass m2)
  {
       return true;
  }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM