Facebook Page Twitter Page LinkedIn Page
× C# Tutorial C# Advanced C# Resources


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 below example, 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.

Note: Here, struct is used instead of class. When class keyword is used, pre-increment and post-increment 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 MyClient {
  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 below example, 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 MyClient {
  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