C# Tutorial C# Advanced C# Resources
Python Java C++ C C# PHP R SQL DS Algo InterviewQ

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: Using class member method

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 MyClient {
  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.


5