Posted by Anuraj on Sunday, October 5, 2014 Reading time :2 minutes
What is extension method
Here is the Wikipedia definition - In object-oriented computer programming, an extension method is a method added to an object after the original object was compiled. The modified object is often a class, a prototype or a type. Extension methods are permitted by some object-oriented programming languages. There is no syntactic difference between calling an extension method and calling a method declared in the type definition.
Extension method introduced in .Net Framework 3.0. The implementation is little different in C# and VB.Net. In C# extension method implemented as static methods in static classes, with the first argument being of extended class and preceded by “this” keyword. And in VB.Net extension method are recognized by the presence of the “extension” keyword or attribute. The most common extension methods are the LINQ standard query operators that add query functionality to the existing System.Collections.IEnumerable and System.Collections.Generic.IEnumerable
Here is a simple extension methods, which reverses a string.
If you look into the code, by default string doesn’t have a method like Reverse. And you can find a static class Extensions, which has a Reverse() static method, with the first argument being of extended class and preceded by “this” keyword, it an a extension method for string class. Because of this, compiler will compile the source without any problem.
How it works.
If you look into the IL code generated using IL Disassembler, you can find a type like Extensions which is decorated with ExtensionAttribute, this is the same attribute you need to create an extension method in VB.Net. In C#, if you use this modifier for the first parameter of extension method, compiler will automatically emit ExtensionAttribute for the methods.
And in the consuming code, it is like invoking a static method.
General guidelines to implement Extension Methods
Happy Coding </t>
What do you think? I would like to hear your thoughts, suggestions, and questions in the comments section below.