Search This Blog

2013/11/08

Extension Method in C#?


Extension method is special kind of static method in c# which even though defined as static can be called as if instance methods. It is new feature in C# 3.0 or .Net 3.5
    Most fascinating thing about extension method is it let us to add a new method to existing type (class or interface) without modifying it or creating a derived type. It can be used to extend any type in the .NET Framework or any custom type.
How to Define Custom Extension Method?
Consider code below where we are defining a static class ‘MyStringHelper’  in which we are defining an extension method called ‘SplitCamelCase’.
The first parameter here ‘string’  which specifies it operates on string type or in other word it going to extend existing type called ‘string’, but its syntax says it always need to be preceded by the ‘this’ modifier.
  I am creating a console application and adding a new class to it namely Class1.cs.
Code in both files listed below showing implementation of extension method with 

       1)      Native .Net Type string
       2)      Custom Class
       3)      Custom Interface

[Program.cs]
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using OtherExtensionMethodNamespace;
using System.Text.RegularExpressions;

namespace ExtensionMethod
{
    class Program
    {
        static void Main(string[] args)
        {
            MyMath MyMathObj= new MyMath();
            IIntMath IIntMathObj = new IntMath();

            Console.WriteLine("Call to Extended Method On Class Implementing Interface:" + IIntMathObj.SubstractInt(10, 2).ToString());
            Console.WriteLine("Call to Extended Method on Class:" + MyMathObj.addIntMinusOne(10,2).ToString());

            Console.WriteLine( "Call to extension Method on Native String Type:" +"cameraMountedGoogleCarOnStreet".SplitCamelCase());
            Console.ReadKey();
        }
    }
   
    /*extension methods in same namespace*/

    /*Extension method & Interface*/
    interface IIntMath
    {
        int addInt(int i, int j);
    }
    class IntMath : IIntMath
    {
        public int addInt(int i, int j)
        {
          return  i + j;
        }
    }

    /*Extension method & custom type*/
    class MyMath
    {
        public int addIntPlusOne(int i, int j)
        {
            return i + j+1;
        }
    }
  

    /*Extension method & .net type*/
    static class StringHelper65
    {
        public static string SplitCamelCase(this string str)
        {
            return Regex.Replace(Regex.Replace(str, @"(\P{Ll})(\P{Ll}\p{Ll})", "$1 $2"), @"(\p{Ll})(\P{Ll})", "$1 $2");
        }
    }
}

[Class1.cs]
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ExtensionMethod;

/*extension methods Written in Other namespace*/
namespace OtherExtensionMethodNamespace
{
    static class StringHelper45
    {
        public static int addIntMinusOne(this MyMath MyMathObj, int i, int j)
        {
            return i - j - 1;
        }

        public static int SubstractInt(this IIntMath IntMathObj, int i, int j)
        {
            return i -j;
        }
    }
}
As class StringHelper45 & StringHelper65 are in different namespace we have to add using directive to make required type visible in both files.
Can we override an instance method in given type by the Extension Method?
When we write an extension method with same signature & name as any instance method whenever we attempt to call the newly created extension method, we are going to use instance method calling syntax as follows 

OurClass OurObj= new OurClass();
OurObj.ExtensionMethodName(); 

But compiler checks if native instance method exists of this name & signature, if so then it will ignore any of its extension method implementation. If no such instance method found then only it uses extension method.
Extension methods always have lower priority than instance methods defined in the type itself.
     Microsoft guideline says that one should use extension methods sparingly. Whenever possible, client code that must extend an existing type should do so by creating a new type derived from the existing type.
   Extension method are used to write custom html helper like html.textboxfor in mvc.

No comments:

Post a Comment