Sunday, June 26, 2011

Extension method for IComparable

.net

Extension method for IComparable

C# 3.0 gives great feature of extension method. I am also very much interested for Extension method.  Today, My friend Divyang posts very useful topic "Extension Meathod for IComparable".  I would like to share you something interesting way to use that extension method. This time it's extending IComparable. The API signature for IComparable<T> 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 Here we have 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<T>
    {
        return left.CompareTo(right) > 0;
    }

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

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

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

    public static bool Equal(this T left, T right) where T : IComparable<T>
    {
        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.

No comments:

Post a Comment