Extension Method

Extension method is a feature in c# 3.0, which allows developer to add functionality in existing class without modifying the existing class or recompiling the existing class or extending the existing class.

exte1.gif
            exte1.1.gif

Few Points about Extension method

  1. It is a new feature of c#3.0
  2. Extension method enables to add new methods to existing type. It does not need creation of derived type to existing type, modifying the original type or recompiling the original type.
  3. It provides ability to programmer to add new methods to existing type.
  4. It can be used to add new methods to existing .Net core classes.
  5. It is defined as a static method but called with syntax of instance method.
  6. If there is a member method in type class with the same name of extension method then member method will get precedence over extension method.

    For example Show method is member method of Message class. So if there is any extension method called Show on type Message class is created, always Show member method will get precedence over Show extension method for the type Message.

Compiler signature of Extension Method

static class Extensions
{
 
public static IEnumerable<T> Where<T>(this IEnumerable<T> sequence, Predicate<T> predicate)
  {
    
foreach (T item in sequence)
     {
       
if (predicate(item))
        {
           
yield return item;
        }
      }
   }
}

  1. The method is static
  2. The first parameter is decorated with modifier "this" .
  3. First parameter is called as Instance Parameter.
  4. A compile time error will encountered to use this modifer with any other parameter than instance parameter.
  5. No other modifers like ref, out etc are allowed with "this" modifer or instance parameter.
  6. The instance parameter can not be a pointer type.
  7. The method is public .
  8. The instance parameter can not have the type of the type parameter. The below is not possible.

    public static int Obj<T> (this T param)

Restrictions on Extension methods

  1. It could only access public memebers of the target type.
  2. If an extension method conflicts with a member method of target type , always member method is get invoked instead of extension method.

Implementation and calling of Extension method

Step 1 : Define a static visible class to contain Extension method.

Step 2 : Implement the Extension method as static method.

Step 3: The First parameter of method specifies the type method works on

Step 4 : The First parameter must be preceded by "this" modifer.

Step 5 : At the client code add namespace of extension method with using directive.

Examples on Extension Method

  1. In first example, I will add an Extension method to existing String class. This extension method will remove all the vowel form the string

    exte2.gif
     
  2. Modify the class with modifier with public and static of the class extensionmethodcontainer.
  3. Add a extension method with below signature. The First parameter String specifies that this is extension method on the type String.

    exte3.gif
     
  4. The full code to remove vowel from input string is written in the Extension method.

    ExtensionMethodContainer.cs

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;

    namespace ExtensionMethodSample
    {
        public static class extensionmethodcontainer
        {

            public static String RemoveVowel(this String s)
            {

                string[] vowels = new string[] { "A", "E", "I", "O", "U" };

                if (string.IsNullOrEmpty(s))
                    return string.Empty;

                List<char> chars = new List<char>(s.ToCharArray());
     
                for (int i = chars.Count - 1; i >= 0; i--)
                {
                  
                    for (int j = 0; j < vowels.Length; j++)
                    {
                        if (chars[i].ToString().ToLower() == vowels[j].ToLower())
                            chars.RemoveAt(i);
                    }
                }

                return new string(chars.ToArray());

            }
        }
    }
     

  5. Client code is here Main class
  6. In main class, user is inputting the string and RemoveVowel extension method is being called on the input string to remove vowel from the string.

    Note:
     
    1. Here both Extension method and client is in same namespace, so there is no need to include namespace of the extension method.
    2. Extension method is called as any other member method

       
      resultString = str.RemoveVowel();

Program.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ExtensionMethodSample
{
    class Program
    {
        static void Main(string[] args)
        {
            String resultString;

            Console.WriteLine("Enter Input String to Remove all Vowel using Extension Method \n");
            String str = Console.ReadLine();
            Console.WriteLine("After Removing  Vowel Input String is \n");
            resultString = str.RemoveVowel();
            Console.WriteLine(resultString);
            Console.ReadKey();
        }
    }
}

Output

exte4.gif

Up Next
    Ebook Download
    View all
    Learn
    View all