Operator Overload Example (Relational)

CSharp · Console

/Program.cs

using System;

public class Box
{
  public int Height { get; set; }
  public int Width { get; set; }

  public Box(int h, int w)
  {
    Height = h;
    Width = w;
  }

  public static bool operator <(Box box1, Box box2)
  {
    int area1 = box1.Height * box1.Width;
    int area2 = box2.Height * box2.Width;
    return area1 < area2;
  }
  public static bool operator >(Box box1, Box box2)
  {
    int area1 = box1.Height * box1.Width;
    int area2 = box2.Height * box2.Width;
    return area1 > area2;
  }
}
					
public class Program
{
  public static void Main()
  {
    Box box1 = new Box(15, 32);
    Box box2 = new Box(44, 12);
	
    Console.WriteLine("Is box1 < box2 ? {0}", box1 < box2);
    Console.WriteLine("Is box1 > box2 ? {0}", box1 > box2);
  }
}
;