Extension Method is really a cool stuff. We can simply add the additional method to any object without knowing anything about that object.Let’s say we want a method for string object which will reverse the string then you can choose extension method to do the thing.
Start writing Extension method:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | static class Extension { public static string Reverse(this String input) { char[] inputchar = input.ToCharArray(); for (int i = 0; i < input.Length / 2; i++) { inputchar[i] ^= inputchar[input.Length - 1 - i]; inputchar[input.Length - 1 - i]^=inputchar[i] ; inputchar[i] ^= inputchar[input.Length - 1 - i]; } return new string(inputchar); } } |
Note:
class should be static, Method should be public static and the object on which the method to be added should be passed as parameter preceding by keyword this.
Now you can start to use this method as
1 2 3 4 5 6 7 8 | class Program { static void Main(string[] args) { string s = "ujwal"; Console.WriteLine(s.Reverse()); } } |
I have done extensive use of Extension method while going through Asp.Net MVC project.

January 3rd, 2010 at 10:04 am
Thank you ujwal for cool stuff.
January 9th, 2010 at 8:14 pm
Thank you for the well-written article. I liked it. You have a very nice site.
January 12th, 2010 at 2:19 pm
Don’t we need to add reference to our program? how will it recognize the extension method until there is some way to point out which one to use?
January 13th, 2010 at 8:17 am
Thanks for your valuable comments.
@chota: yes it’s true, the class containig the extension method should be refrenced. Here in the example Extension class is supposed to be in the same namespace.