Explicitcoder

Divyang's ICollection

extention method for IComparable<T>

hello friends,
 C# 3.0 gives great feature of extension method. so i keep playing with this. today  I would like to show you something interesting way to use that extension method. This time it’s extending IComparable. The API signature for IComparable has been around since the birth of  C language . If the left is less than the right, return something less than 0, if left is greater than right, return something greater than 0, and if they are equivalent, return 0. Well, its readability leaves a bit to be desired.
So I wrote this set of extension methods for any type T that implements IComparable:
public static class Hitech.Helper.EquatableExtensions
{
  
    public static bool GreaterThan(this T left, T right) where T : IComparable
    {
        return left.CompareTo(right) > 0;
    }

    public static bool LessThan(this T left, T right) where T : IComparable
    {
        return left.CompareTo(right) < 0;
    }

    public static bool GreaterThanOrEqual(this T left, T right) where T : IComparable
    {
        return left.CompareTo(right) >= 0;
    }

    public static bool LessThanOrEqual(this T left, T right) where T : IComparable
    {
        return left.CompareTo(right) <= 0;
    }

    public static bool Equal(this T left, T right) where T : IComparable
    {
        return left.CompareTo(right) == 0;
    }
}

These methods mean I can write this:
if (obj1.GreaterThan(obj2))
instead of
if (obj1.CompareTo(obj2) > 0)
personally, I find the former much easier to read.
Ok, this is not rocket science, but it’s useful, and it improves the readability of quite a bit of the code I work with on a day to day basis.

compile by
Divyang Panchasara
Sr. Programmer Analyst
Hitech OutSourcing

Leave a Reply

Your email address will not be published. Required fields are marked *