CSharpFeeds - All your C# feeds in one place.

Sponsors

Monday, January 07, 2008

Yet another use for Extension methods : Extending IComparable

by wwagner via Bill Wagner: C# Development Blog | MySmartChannels on 1/7/2008 2:19:00 PM

I keep finding more uses for extension methods. This time it's extending IComparable<T>. The API signature for IComparable<T> has been around since the dawn of C: 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 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 (foo.GreaterThan(bar))

instead of

if (foo.CompareTo(bar) > 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.

email it!bookmark it!digg it!

Original Post: Yet another use for Extension methods : Extending IComparable

Subscribe

New Feed

Product Spotlight

Recently Updated Sources

Legal Note

The content of the postings is owned by the respective author. CSharpFeeds is not responsible for the contents of the postings. This site is automatically generated and cannot be reviewed for abusive content. If you find abusive content on CSharpFeeds, please contact us. Designated trademarks and brands are the property of their respective owners. All rights reserved.

Advertise with us