Extension Methods

Posted: February 23, 2014 in Framework 3.0 New Features
Tags: ,

Simply, you create your own static method in your class and put this keyword in front of the first parameter in this method (the type that will be extended).


public static class MyMathExtension
{
    public static int factorial(<strong>this</strong> int x)
    {
        if (x <= 1) return 1;
        if (x == 2) return 2;
        else
            return x * factorial(x - 1);
    }
}
Complete Code for Demo
namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            int x = 3;
            Console.WriteLine(x.factorial());
            Console.ReadLine();
        }
    }
    public static class MyMathExtension
    {
        public static int factorial(this int x)
        {
            if (x <= 1) return 1;
            if (x == 2) return 2;
            else
                return x * factorial(x - 1);
        }
    }
}

General Guidelines for writing Extension Methods

In general, Microsoft recommend that we implement extension methods sparingly and only when we have to. Whenever possible, client code that must extend an existing type should do so by creating a new type derived from the existing type.

When using an extension method to extend a type whose source code you cannot change, you run the risk that a change in the implementation of the type will cause your extension method to break.

If you do implement extension methods for a given type, remember the following points:

  • An extension method will never be called if it has the same signature as a method defined in the type.
  • Extension methods are brought into scope at the namespace level. For example, if you have multiple static classes that contain extension methods in a single namespace named Extensions, they will all be brought into scope by the using Extensions; directive.
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s