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

5