Extension Method (.Net 3.5 and above)

Posted by in C# category on for Intermediate level | Views : 31438 red flag
Rating: 5 out of 5  
 1 vote(s)

This article describes the use of Extension method in C#.

 Download source code for Extension Method (.Net 3.5 and above)

Extension method is new to C#.Its allow you to add new method to the existing class.

1.Extension method allows you to add new method to the existing class without modifying the code, recompiling or modifying the original code.
2.Extension method are special kind of static method but they are called using instance method syntax. Their first parameter specify which type the method operate on, and the parameter is precede by  “this” modifier.
3.Extension method are only in scope when you explicitly import the namespace into your source code with “using” directive.
For Example in string object there is no method call “Reverse()”  function .But if you need to extend the string ….

Sample Code

C# Code

namespace ExtensionMethods
    public static class ExtensionsClass
        public static string Reverse(this String strReverse)
            char[] charArray = new char[strReverse.Length];
     int len = strReverse.Length - 1;
         for (int i = 0; i <= len; i++)
        charArray[i] = strReverse[len-i];
     return new string(charArray);

C# Code

How to use?

string s = "Hello Extension Methods";
string strReverse = s.Reverse ();

Here "s" is nothing but the parameter of Reverse() method.


Extension method is nothing but the Visitor pattern.

Visitor Pattern:-
Visitor pattern allows us to change the class structure without changing the actual class. Its way of separating the logic and algorithm from the current data structure. Due to this you can add new logic to the current data structure without altering the structure. Second you can alter the structure without touching the logic

Page copy protected against web site content infringement by Copyscape

About the Author

Full Name: Rajkumar Pauldurai
Member Level: Starter
Member Status: Member
Member Since: 5/26/2009 6:29:52 AM

I started my career with Asp,ms-access,sql server 7,xml.Then i updated to .net,share point server,Basics about Biztalk server

Login to vote for this post.

Comments or Responses

Login to post response

Comment using Facebook(Author doesn't get notification)