How to declare natural ordering by overriding the comparison operators in C# .NET
May 15, 2015 1 Comment
In this post we saw one way to declare natural ordering for a custom class by implementing the generic IComparable of T interface. In this post we’ll look at how to achieve the same by overriding the 4 comparison operators:
< > <= >=
We’ll go with our Triangle class like before where we said that natural ordering should be based on the area of the Triangle:
public class Triangle
{
public double BaseSide { get; set; }
public double Height { get; set; }
public double Area
{
get
{
return (BaseSide * Height) / 2;
}
}
}
We’ll need to implement all 4 equality operators otherwise the compiler will complain:
public static bool operator <(Triangle triangleOne, Triangle triangleTwo)
{
return triangleOne.Area < triangleTwo.Area;
}
public static bool operator >(Triangle triangleOne, Triangle triangleTwo)
{
return triangleOne.Area > triangleTwo.Area;
}
public static bool operator <=(Triangle triangleOne, Triangle triangleTwo)
{
return triangleOne.Area <= triangleTwo.Area;
}
public static bool operator >=(Triangle triangleOne, Triangle triangleTwo)
{
return triangleOne.Area >= triangleTwo.Area;
}
Let’s test this:
Triangle tOne = new Triangle() { BaseSide = 4, Height = 2 };
Triangle tTwo = new Triangle() { BaseSide = 5, Height = 3 };
Triangle tThree = new Triangle() { BaseSide = 6, Height = 2 };
Triangle tFour = new Triangle() { BaseSide = 7, Height = 2 };
Debug.WriteLine(tOne > tTwo);
Debug.WriteLine(tTwo <= tThree);
Debug.WriteLine(tFour < tOne);
Debug.WriteLine(tTwo >= tFour);
This will print
False
False
False
True
…in the output window which is the correct result.
View all various C# language feature related posts here.
Reblogged this on Dinesh Ram Kali..