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

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 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();
    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