Extension Methods

Apparently I completely missed the introduction of the extension methods feature with .NET 3.5/CLR 2.0/C#. It's not doing anything new from the old version of the CLR per se, but it is very handy syntactic sugar. Basically it takes a static method and uses the first argument to fake out a thiscall.

using System;
using System.Runtime.CompilerServices;

namespace ExtensionMethods
{
    public static class ExtensionMethods
    {
        [Extension]
        public static void PrintMe(this string someString)
        {
            Console.WriteLine(someString);
        }
    }
}
using System;

namespace ExtensionMethods
{
    static class Program
    {
        [STAThread]
        static void Main()
        {
            string coolString = "hello world";
            coolString.PrintMe();                   // pretty neat!
        }
    }
}

0 comments: