C# Tutorial C# Advanced C# References

C# - Unary Operator Overloading



Unary operators are those operators which acts upon a single operand to produce a new value. Following is the list of unary operators that can be overloaded in C#.

Overloadable unary operators in C#
+-truefalse
++--!~

The unary operators is used with object in the same way as it is used normally. The operator normally precedes object in the expression like - !obj, -obj, and ++obj but sometimes it can be used as postfix as well like obj++ or obj--.

Example: overloading unary minus (-) operator

In the example below, unary minus operator is overloaded. When it is used with vector object, it applies negation on x and y component of the object, for example - applying negation on (10, 15) will produce (-10, -15).

using System;

class vector {
  //class fields
  int x;
  int y;

  //class constructors
  public vector(){}
  public vector(int a, int b) {
    x = a; 
    y = b;
  }

  //method to display vector
  public void displayVector() {
    Console.WriteLine("({0}, {1})", x, y);
  }

  //method for overloading unary minus
  public static vector operator- (vector v1) {
    return new vector(-v1.x, -v1.y);    
  }    
}

class Implementation {
  static void Main(string[] args) {
    vector v1 = new vector(10, 15);
    vector v2;

    v2 = -v1;
    v2.displayVector();
  }
}

The output of the above code will be:

(-10, -15)

❮ C# - Operator Overloading