Overloading Relational Operators : Relotional Operator Overload « Operator Overload « C# / CSharp Tutorial






using System;

public class Employee: IComparable
{
    public Employee(string name, int id)
    {
        this.name = name;
        this.id = id;
    }
    
    int IComparable.CompareTo(object obj)
    {
        Employee emp2 = (Employee) obj;
        if (this.id > emp2.id)
        return(1);
        if (this.id < emp2.id)
        return(-1);
        else
        return(0);
    }
    public static bool operator <(Employee emp1, Employee emp2)
    {
        IComparable icomp = (IComparable) emp1;
        return(icomp.CompareTo (emp2) < 0);
    }
    public static bool operator >(Employee emp1,Employee emp2)
    {
        IComparable    icomp = (IComparable) emp1;
        return(icomp.CompareTo (emp2) > 0);
    }
    public static bool operator <=(Employee emp1,Employee emp2)
    {
        IComparable    icomp = (IComparable) emp1;
        return(icomp.CompareTo (emp2) <= 0);
    }
    public static bool operator >=(Employee emp1,Employee emp2)
    {
        IComparable    icomp = (IComparable) emp1;
        return(icomp.CompareTo (emp2) >= 0);
    }
    
    public override string ToString()
    {
        return(name + ":" + id);
    }
    
    string    name;
    int    id;
}
class Test
{
    public static void Main()
    {
        Employee a = new Employee("A", 1);
        Employee b = new Employee("B", 2);
        Employee c = new Employee("C", 4);
        Employee d = new Employee("D", 3);
        
        Console.WriteLine("a < b: {0}", a < b);
        Console.WriteLine("c >= d: {0}", c >= d);
    }
}
a < b: True
c >= d: True








8.3.Relotional Operator Overload
8.3.1.Overload > and <
8.3.2.Overloading Relational Operators