C# Tutorial C# Advanced C# References

C# - Increment & Decrement Operator Overloading



The increment (++) and decrement (--) are two important unary operators in C#. Each operator has two variant:

  • Pre-increment & Post-increment
  • Pre-decrement & Post-decrement

Example: overloading increment operator

In the example below, increment operator is overloaded. When it is used with vector object, it increases x and y component of the object by 1, for example - applying pre-increment operator on (10, 15) will produce (11, 16) before it is used, and applying post-increment on (10, 15) will produce (11, 16) after it is used.

using System;

class vector {
  int x;
  int y;
  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 ++
  public static vector operator++ (vector v1) { 
    v1.x++;
    v1.y++;
    return v1;    
  }    
}

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

    v2 = ++v1;
    v1.displayVector();
    v2.displayVector();

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

The output of the above code will be:

(11, 16)
(11, 16)
(12, 17)
(11, 16)

Example: overloading decrement operator

In the example below, decrement operator is overloaded. When it is used with vector object, it decreases x and y component of the object by 1, for example - applying pre-decrement operator on (10, 15) will produce (9, 14) before it is used, and applying post-decrement on (10, 15) will produce (9, 14) after it is used.

Note: Here, struct is used instead of class. When class keyword is used, pre-decrement and post-decrement will produce same result.

using System;

struct vector {
  int x;
  int y;
  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 --
  public static vector operator-- (vector v1) { 
    v1.x--;
    v1.y--;
    return v1;    
  }    
}

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

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

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

The output of the above code will be:

(9, 14)
(9, 14)
(8, 13)
(9, 14)

❮ C# - Operator Overloading