Thursday 23 June 2011

Extention method for IComparable


Hi 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<T>. 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 I wrote this set of extension methods for any type T that implements IComparable<T>:
public static class Hitech.Helper.EquatableExtensions
{
  
    public static bool GreaterThan<T>(this T left, T right) where T : IComparable<T>
    {
        return left.CompareTo(right) > 0;
    }

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

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

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

    public static bool Equal<T>(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