Operator Overloading in C#

Up Java Resources C++ Resources Comp410

Operator overloading permits user-defined operator implementations to be specified for operations where one or both of the operands are of a user-defined class or struct type. Operator overloading makes a program clearer than accomplishing the same operations with explicit method calls. However, it is not possible to overload all operators in C#.

In C#, a special function called operator function is used for overloading purpose. These special function or method must be public and static. They can take only value arguments.

public static returnType operator +(ParamList,....,....)
{
    //Implementation of the operator
}

The following program overloads the unary '-' operator inside the class Complex :

class Complex
{
 private int realPart;
 private int imgPart;
 public Complex()
 {
 } 
 public Complex(int i, int j)
 {
  realPart = i;
  imgPart = j;
 }

 public static Complex operator -(Complex c)
 {
  Complex temp = new Complex();
  temp.realPart = -c.realPart;
  temp.imgPart = -c.imgPart;
  return temp;
 }
}