Pages

Wednesday, July 13, 2011

Extension Methods in C#

using System;

namespace Foo
{
   class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine(2.DoubleThenAdd(3));
            Console.WriteLine(IntHelper20.DoubleThenAdd(2, 3));
            Console.ReadLine();
        }
    }

    public static class IntHelper20
    {
        public static int DoubleThenAdd(int myInt, int x)
        {
            return myInt + (2 * x);
        }
    }

    public static class IntHelper35
    {
        public static int DoubleThenAdd(this int myInt, int x)
        {
            return myInt + (2 * x);
        }
    }
}



Source: http://www.hanselman.com/blog/HowDoExtensionMethodsWorkAndWhyWasANewCLRNotRequired.aspx

No comments:

Post a Comment