Csharp/CSharp Tutorial/Operator Overload/Relotional Operator Overload
Overload > and
<source lang="csharp">using System;
class TwoDimension {
int x, y; public TwoDimension() { x = y = 0; } public TwoDimension(int i, int j) { x = i; y = j; } // Overload <. public static bool operator <(TwoDimension op1, TwoDimension op2) { if((op1.x < op2.x) && (op1.y < op2.y)) return true; else return false; } // Overload >. public static bool operator >(TwoDimension op1, TwoDimension op2) { if((op1.x > op2.x) && (op1.y > op2.y)) return true; else return false; } // Show X, Y public void show() { Console.WriteLine(x + ", " + y); }
}
class TwoDimensionDemo {
public static void Main() { TwoDimension a = new TwoDimension(5, 6); TwoDimension b = new TwoDimension(10, 10); TwoDimension c = new TwoDimension(1, 2); Console.Write("Here is a: "); a.show(); Console.Write("Here is b: "); b.show(); Console.Write("Here is c: "); c.show(); Console.WriteLine(); if(a > c) Console.WriteLine("a > c is true"); if(a < c) Console.WriteLine("a < c is true"); if(a > b) Console.WriteLine("a > b is true"); if(a < b) Console.WriteLine("a < b is true"); }
}</source>
Here is a: 5, 6 Here is b: 10, 10 Here is c: 1, 2 a > c is true a < b is true
Overloading Relational Operators
<source lang="csharp">using System; public class Employee: IComparable {
public Employee(string name, int id) { this.name = name; this.id = id; } int IComparable.rupareTo(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.rupareTo (emp2) < 0); } public static bool operator >(Employee emp1,Employee emp2) { IComparable icomp = (IComparable) emp1; return(icomp.rupareTo (emp2) > 0); } public static bool operator <=(Employee emp1,Employee emp2) { IComparable icomp = (IComparable) emp1; return(icomp.rupareTo (emp2) <= 0); } public static bool operator >=(Employee emp1,Employee emp2) { IComparable icomp = (IComparable) emp1; return(icomp.rupareTo (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); }
}</source>
a < b: True c >= d: True