Extension Method in C# 3.0

No.of Views1045
Bookmarked0 times
Downloads 
Votes0
By  Dhananjay Kumar   On  16 Feb 2010 00:02:56
Tag : CSharp , Miscellaneous
This article will explain about Extension method with a complete example.
emailbookmarkadd commentsprint

Images in this article missing? We recently lost them in a site migration. We're working to restore these as you read this. Should you need an image in an emergency, please contact us at info@codegain.com

 

Introduction

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.

Image Loading

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

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

 

Image Loading

3. Modify the class with modifier with public and static of the class extensionmethodcontainer.

4. Add a extension method with below signature. The First parameter String specifies that this is extension method on the type String.

Image Loading

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

6. Client code is here Main class
7. 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

Image Loading

 

Sample Project Source

Download source files -23 kb

 
Sign Up to vote for this article
 
About Author
 
Dhananjay Kumar
Occupation-Software Engineer
Company-Infosys Technolgies,Pune
Member Type-Gold
Location-India
Joined date-20 Jul 2009
Home Page-http://dhananjaykumar.net/
Blog Page-http://dhananjaykumar.net/
Dhananjay Kumar is Microsoft MVP on connected system. He blogs at http://dhananjaykumar.net/ . You can follow him http://twitter.com/debugmode_/ and reach him at dhananjay.25july@gmail.com
 
 
Other popularSectionarticles
Comments
There is no comments for this articles.
Leave a Reply
Title:
Display Name:
Email:
(not display in page for the security purphase)
Website:
Message:
Please refresh your screen using Ctrl+F5
If you can't read this number refresh your screen
Please input the anti-spam code that you can read in the image.
^ Scroll to Top