Understanding Extension Methods in .Net
Open Source Your Knowledge, Become a Contributor
Technology knowledge has to be shared and made accessible for free. Join the movement.
Did you know that you can extend the functionality of any class or type from the .Net framework or any external library without having to obtain the source code?
Yes, this is doable. You can write methods that extend the existing functionality and call these methods as if they are part of the framework or the external library. The same also applies for your own classes.
This is the power of .Net extension methods.
Extension methods is a very useful feature that was added in .Net framework 3.0 that gives the developer the ability to add or extend methods to existing types without creating a new derived type, recompiling, or modifying the original type.
Once you write an extension method you can call it as if it was an instance method of the existing type.
In this article we will be discussing the uses of the extension methods, the structure and rules for writing extension methods, with different samples of in-browser runnable C# code snippets with unit tests, that illustrate the way to implement it in code, after that we will blend the extension methods with generics to show the ultimate usage of such extensiblity feature in .Net and illustrate it with another code sample, we will also take a look at the open source huge library of extension methods available on github.
So let's get started!