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.

  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.
    It is defined as a static method but called with syntax of instance method.
  5. 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

 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

  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

Step1 : Define a static visible class to contain Extension method. 

Step2: Implement the Extension method as static method. 

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

Step4 : The First parameter must be preceded by “this” modifer. 

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

 Examples

  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  

  1. Modify the class with modifier with public and static of the class extensionmethodcontainer. 
  2. Add a extension method with below signature. The First parameter String specifies that this is 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.

 

    1 using System;

    2 

    3 using System.Collections.Generic;

    4 

    5 using System.Linq;

    6 

    7 using System.Text;

    8 

    9 namespace ExtensionMethodSample

   10 {

   11 public static class extensionmethodcontainer

   12 {

   13 

   14 public static String RemoveVowel(this String s)

   15 {

   16 string[] vowels = new

   17 

   18 string[] { “A”, “E”, “I”, “O”, “U” };

   19 

   20 if (string.IsNullOrEmpty(s))

   21 return string.Empty;

   22 

   23 List<char> chars = new List<char>(s.ToCharArray());

   24 for (int i = chars.Count – 1; i >= 0; i–)

   25   {

   26        for (int j = 0; j < vowels.Length; j++)

   27             {

   28 

   29                     if (chars[i].ToString().ToLower() == vowels[j].ToLower())

   30 

   31                         chars.RemoveAt(i);

   32              }

   33             }

   34 

   35 return new string(chars.ToArray());

   36 

   37 }

   38 

   39 }

   40 

   41 }

   42 

  1. Client code is here Main class
  2. 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();

    1 using System;

    2 using System.Collections.Generic;

    3 using System.Linq;

    4 using System.Text;

    5 namespace ExtensionMethodSample

    6 {

    7 class Program

    8 {

    9 static void Main(string[] args)

   10 {

   11 String resultString;

   12 

   13 Console.WriteLine(“Enter Input String to Remove all Vowel using Extension Method \n”);

   14 

   15 String str = Console.ReadLine();

   16 

   17 Console.WriteLine(“After Removing Vowel Input String is \n”);

   18 

   19 resultString = str.RemoveVowel();

   20 

   21 Console.WriteLine(resultString);

   22 

   23 Console.ReadKey();

   24 }

   25 }

   26 }

   27 }

   28 


 

Happy Coding

About these ads

3 thoughts on “Extension Method

  1. Pingback: Monthly Report March 2010: Total Posts 6 « debug mode……

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s