Learn About Extension Methods

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.

  1. public static type ExtensionMethod (this int param, params...)  
  2.         {  
  3.           // instructions  
  4.         } 

 

To use this extension:

  1. int i;  
  2. 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