Click here to Skip to main content
15,881,757 members
Articles / Programming Languages / C# 4.0

Extension Method (Basic Understanding)

Rate me:
Please Sign up or sign in to vote.
3.22/5 (5 votes)
12 Jun 2009CPOL3 min read 18.5K   85   15   4
Extension method is a feature in C# 3.0, which allows a developer to add functionality in existing class without modifying or recompiling or extending the existing class.

Introduction

This is a new feature in C# 3.0 that helps to extend existing classes like .NET core classes which cannot be extended. You may need to add functionality without extending the class, or recompiling the existing class or modifying the existing method.

Few Points on ExtensionMethods

  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 the ability to the 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 the syntax of an 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 a member method of Message class. So if there is any extension method called Show on type Message class that is created, always Show member method will get precedence over Show extension method for the type Message.

Using the Code

Compiler signature of Extension method is as follows: 

C#
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. The first parameter is called as Instance Parameter.
  4. A compile time error will be 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 cannot be a pointer type.
  7. The method is public.
  8. The instance parameter cannot have the type of the type parameter.  The below is not possible:
    C#
    public static int Obj<T> (this T param)

Restrictions on Extension Methods

  1. It could only access public members of the target type.
  2. If an Extension method conflicts with a member method of target type, always member method gets invoked instead of Extension method.

Implementation and Calling of Extension Method

  1. Define a static visible class to contain Extension method.
  2. Implement the Extension method as static method.
  3. The first parameter of method specifies the type method works on.
  4. The first parameter must  be preceded by “this” modifer.
  5. At the client code, add namespace of Extension method with using directive.

Examples of Extension Method

In the first example, I will add an Extension method to the existing String class. This Extension method will remove all the vowels from the string.  

Modify the class with modifiers public and static of the class extensionmethodcontainer.

Add an Extension method with the below signature. The first parameter String specifies that this is an Extension method on the type String.

C#
public static String RemoveVowel(this String s)

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

ExtensionMethodContainer.cs

C#
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()); 
        } 
    } 
}

Client code is in the Main class.

In the main class, user inputs the string and RemoveVowel Extension method is called on the input string to remove vowel from the string.

Note

  1. Here both Extension method and client are in the same namespace, so there is no need to include namespace of the Extension method.
  2. Extension method is called as any other member method.
    C#
    resultString = str.RemoveVowel();

Program.cs

C#
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(); 
        } 
    } 
}

History

  • 12th June, 2009: Initial post

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
United States United States
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
Suggestionsmall change in code Pin
kirtikk5-Sep-12 2:29
kirtikk5-Sep-12 2:29 
GeneralMy vote of 2 Pin
John Whitmire16-Jun-09 3:57
professionalJohn Whitmire16-Jun-09 3:57 
GeneralPlease get someone to proofread your English. Will improve readability heaps. Pin
OberGruppenFuhrer12-Jun-09 19:53
OberGruppenFuhrer12-Jun-09 19:53 
GeneralWhat do you like to express with the choice of user name ? Pin
cwp4216-Jun-09 3:18
cwp4216-Jun-09 3:18 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.