Monday, May 24, 2010

Extension Methods - .Net 3.0 or later

1.       Extension method allows you to add new method to a class without modifying the existing class. We can add new method to a sealed class well. 

2.       Extension method is special kind of static methods. The first parameter specifies which type the method operates on. Also the parameter is preceded by “this” modifier. We cannot use the ‘this’ keyword in a normal static method. But to define the extension method we have to use ‘this’ key word with the first parameter of that method. For e.g. ‘string’ does not have any in build method to reverse the string. Now let’s say we want to add a new method to reverse the string. 

    public static class MyExtensionMethodClass

    {

        /// <summary>

        /// This is a extension method to reverse the string

        /// </summary>

        /// <param name="input">Input string to revese</param>

        /// <returns>Reversed string</returns>

        public static string Reverse(this string input)

        {           

            int length = input.Length;

            StringBuilder inputString = new StringBuilder(input);

 

            for (int index = 0; index < length / 2; index++)

            {

                char character = inputString[index];

                inputString[index] = inputString[length - index - 1];

                inputString[length - index - 1] = character;

            }

 

            return inputString.ToString();

        }

    }

 

Now when you ‘string’ class it would show you a new method as shown below.

image 

3.       Extension method is like a visitor pattern which allows you to change class structure without changing the actual class. You can alter the structure without changing the logic.

4. Extension method cannot be used to override the original method. If there is already a method with same name & signature as extension method then the original method would be called rather than the extension method. This is because it first looks for a match in the type's instance methods. If no match is found, it will search for any extension methods that are defined for the type, and bind to the first extension method that it finds

          An extension method will never be called if it has the same signature as a method defined in the type. For e.g.

    class Program

     {

         static void Main(string[] args)

         {

             MyClass obj = new MyClass();

             obj.MyFun();

 

             Console.ReadKey();

         }

     }

 

     public static class MyExtensionMethodClass

     {

         public static void MyFun(this MyClass obj)

         {

             Console.WriteLine("Inside Extension method");

         }

     }

 

     public class MyClass

     {

         public void MyFun()

         {

             Console.WriteLine("Inside class MyClass.MyFun");

        }

     }

/*

Output :-

Inside class MyClass.MyFun

*/

No comments: