Hello C# beginners. In this blog, we will see what an extension method via a concrete example.
Why use extension Methods?
If we need to add a method called ExtensionMethod to Int class: we should create a derivative class and add our methods to it, correct?
The response is NO: Because int class is sealed so we can’t inherit from it but .NET framework contains a powerful solution which is “Extension Methods.”
How could we do that?
To add an extension Method of int type, add a static method, the first attribute type must be (this int)
This is used to specify that int is our extended Type.
- public static type ExtensionMethod (this int param, params...)
- {
-
- }
To use this extension:
- int i;
- i.ExtensionMethod(params ..)
Advantages
No Need to create a derivate class.
No need to change original class.
No need to recompile.
Calling of an extension method is simple.
For more details, you can read the links below.
- https://msdn.microsoft.com/en-us/library/bb383977.aspx
- https://msdn.microsoft.com/en-us/library/bb311042.aspx