C# Tutorial C# Advanced C# References

C# - Operator Overloading



With operator overloading feature in C#, we can make operators to work for user-defined classes. As we create a class, it creates a new type in the code and C# allows us to specify the operators with a special meaning for a data type, this ability is known as operator overloading. For example - '+' operator can be overloaded for a string class to concatenate two strings.

Overloaded operators are method with special name. The name starts with keyword operator followed by operator symbol. Like any other method, the overloaded operator has return type and passing arguments.

The declaration of method for overloading of operator + is given below. The return type of the method is vector and it requires two argument (two vector objects) to pass.

vector operator+ (vector v1, vector v2)

Example: overloading + operator

The example below describes how to overload + operator to add two vectors. Here, the vector v1 is taken as (10, 15) and vector v2 is taken as (5, 25). The addition operation of v1 and v2 creates v3 which is (10+5, 15+25) or (15, 40).

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 +
  public static vector operator+ (vector v1, vector v2) {
    vector temp = new vector();
    temp.x =  v1.x + v2.x;
    temp.y =  v1.y + v2.y;  
    return temp;    
  }    
}

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

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

The output of the above code will be:

(15, 40)

Overloadable operators in C#

Following is the list of operators that can be overloaded in C#.

Overloadable operators in C#
+-++--!~
truefalse*/<>
==<<>>,^ (binary)!=
<=>=%&|

Note: Please note that certain operators must be overloaded in pairs, for example (< and >) must be overloaded in pairs.

Non-overloadable operators in C#

Here is the list of operators that can not be overloaded in C#.

Non-overloadable operators in C#
&&||[]()+=-=
*=/=%=&=|=^=
^ (unary)=.?.?:??
??=..<<=>>=->=>
f(x)asawaitcheckedunchecked

Operator Overloading Examples

Here is the list of various operator overloading examples which can be used to understand the concept more deeply.