Saturday, April 5, 2008

The joy of Extension Methods in C# 3.0

I discovered a new addition to C# 3.0 called Method Extension while I was writing a convertor for Hex and Binary for Cosmos today. Method Extension is a technique for "spot-welding" methods on to existing classes or types.


    //Without C# 3.0 Method Extension
    if (IsOdd(7))
        ;
 
    //With C# 3.0 Method Extension
    if (7.IsOdd())
        ;


Here the I've added the IsOdd method onto an integer type. I think the lower example is a lot easier to read than the upper.

Adding an extended method is as simple as adding 'this' keyword on the first parameter on a static method inside a static class, like this:


public static class IntExtender
    {
        /// 
        /// Checks if number is odd or even.
        /// 
        public static bool IsOdd(this int n)
        {
            if ((n % 2) > 0)
                return true;
            else
                return false;
        }
    }


Method Extensions requires a reference to System.Data.Core assembly in your project.


The Intellisense looks like this:














By adding extensions in Cosmos we can now directly convert numbers to Hex and Binary like this:

foreach (byte b in bytes)
    {
        Console.Write(b.ToBinary());
        Console.Write(b.ToHex());
    }

No comments: