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#

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 MyClient {
  static void Main(string[] args) {
    Vector v1 = new Vector(10, 15);
    Vector v2;

    v2 = -v1;

The output of the above code will be:

(-10, -15)

❮ C# - Operator Overloading