Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

Extension Method (Basic Understanding)

0.00/5 (No votes)
12 Jun 2009 1  
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: 

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:
    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.

public static String RemoveVowel(this String s)

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

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

History

  • 12th June, 2009: Initial post

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here