How to declare natural ordering by overriding the comparison operators in C# .NET

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.

Advertisement

About Andras Nemes
I'm a .NET/Java developer living and working in Stockholm, Sweden.

One Response to How to declare natural ordering by overriding the comparison operators in C# .NET

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

Elliot Balynn's Blog

A directory of wonderful thoughts

Software Engineering

Web development

Disparate Opinions

Various tidbits

chsakell's Blog

WEB APPLICATION DEVELOPMENT TUTORIALS WITH OPEN-SOURCE PROJECTS

Once Upon a Camayoc

Bite-size insight on Cyber Security for the not too technical.

%d bloggers like this: