C# Tutorial C# Advanced C# References

C# - Relational Operator Overloading



Relational operators are those operators which compares two operand, like operators (==, <, >, <=, >=) compares C# data types. C# allows us to specify these operators with a special meaning for a class object.

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

Example: overloading relational operators

In the example below, relational operators < and > are overloaded. When it is applied with point objects, it compares its distance from origin and returns true or false based on the comparison result. For example:

  • (10, 15) > (5, 25) will compare 10² + 15² > 5² + 25² which is equivalent to 325 > 650, hence returns false.
  • (10, 15) < (12, 14) will compare 10² + 15² < 12² + 14² which is equivalent to 325 < 340, hence returns true.
using System;

class point {
  //class fields
  int x;
  int y;

  //class constructors
  public point(){}
  public point(int a, int b) {
    x = a; 
    y = b;
  }

  //method for overloading <
  public static bool operator< (point p1, point p2) {
    Double d1 = Math.Sqrt(p1.x * p1.x + p1.y * p1.y);
    Double d2 = Math.Sqrt(p2.x * p2.x + p2.y * p2.y);
    return d1 < d2 ? true : false;
  }

  //method for overloading >
  public static bool operator> (point p1, point p2) {
    Double d1 = Math.Sqrt(p1.x * p1.x + p1.y * p1.y);
    Double d2 = Math.Sqrt(p2.x * p2.x + p2.y * p2.y);  
    return d1 > d2 ? true : false;
  }      
}

class Implementation {
  static void Main(string[] args) {
    point p1 = new point(10, 15);
    point p2 = new point(5, 25);
    point p3 = new point(12, 14);

    Console.WriteLine("(p1 > p2) returns: {0}", (p1 > p2));
    Console.WriteLine("(p1 < p3) returns: {0}", (p1 < p3));
  }
}

The output of the above code will be:

(p1 > p2) returns: False
(p1 < p3) returns: True

❮ C# - Operator Overloading