How extension method works in .Net
October 05, 2014 by Anuraj
.Net .Net 3.0 / 3.5 Visual Studio
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
- An extension method will never be called if it has the same signature as a method defined in the type.
- Extension methods are brought into scope at the namespace level.
Happy Coding </t>
Copyright © 2024 Anuraj. Blog content licensed under the Creative Commons CC BY 2.5 | Unless otherwise stated or granted, code samples licensed under the MIT license. This is a personal blog. The opinions expressed here represent my own and not those of my employer. Powered by Jekyll. Hosted with ❤ by GitHub