C# Tutorial C# Advanced C# References

C# - Binary Operator Overloading



Binary operators are those operators which requires two operand to produce a new value. Following is the list of binary operators that can be overloaded in C#.

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

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

Example: overloading binary operators

In the example below, binary operators - +, -, *, and / are overloaded. When it is applied with vector objects, it performs addition, subtraction, multiplication and division component wise. For example:

  • (10, 15) + (5, 25) will produce (10+5, 15+25) = (15, 40)
  • (10, 15) - (5, 25) will produce (10-5, 15-25) = (5, -10)
  • (10, 15) * (5, 25) will produce (10*5, 15*25) = (50, 375)
  • (10, 15) / (5, 25) will produce (10/5, 15/25) = (2, 0.6)
using System;

class vector {
  //class fields
  float x;
  float y;

  //class constructors
  public vector(){}
  public vector(float a, float b) {
    x = a; 
    y = b;
  }

  //method to display vector
  public void displayVector() {
    Console.WriteLine("({0}, {1})", x, y);
  }

  //method for overloading binary +
  public static vector operator+ (vector v1, vector v2) { 
    return new vector(v1.x + v2.x, v1.y + v2.y);    
  } 

  //method for overloading binary -
  public static vector operator- (vector v1, vector v2) {
    return new vector(v1.x - v2.x, v1.y - v2.y);   
  } 

  //method for overloading binary *
  public static vector operator* (vector v1, vector v2) {
    return new vector(v1.x * v2.x, v1.y * v2.y);    
  } 

  //method for overloading binary /
  public static vector operator/ (vector v1, vector v2) {
    if (v2.x == 0 || v2.y == 0) {
      throw new DivideByZeroException();
    }
    return new vector(v1.x / v2.x, v1.y / v2.y);    
  }     
}

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

    //using overloaded binary operators
    v3 = v1 + v2 ;
    v3.displayVector();
    v3 = v1 - v2 ;
    v3.displayVector();
    v3 = v1 * v2 ;
    v3.displayVector();
    v3 = v1 / v2 ;
    v3.displayVector();
  }
}

The output of the above code will be:

(15, 40)
(5, -10)
(50, 375)
(2, 0.6)

❮ C# - Operator Overloading

5