Extension Method In C#

Introduction

 
Extension Method in C# has been added in 3.0. It allows us to add new methods in the existing class or in the structure without modifying the source code of the original type. In the process we do not require any permission from the original type and the original type does not require any re-compilation.
 
Through inheritance we can extend the functionalities; however, it has a few limitations.
  1. If the class is sealed we cannot follow the inheritance mechanism
  2. If the original type is not a class but a structure, inheritence is not possible at all.  
So let's disscuss how we could add methods for existing class.
 
Step 1
 
Add a new class and it should be a static class .
  1. static class GetCount  
  2. {  
  3.    //Add Method as shown in Step 2  
  4. }   
Step 2
 
Add a static method to the class and bind the method to the existing class or structure we want.
  1. static class GetCount  
  2. {  
  3.    // We are extending the method of sting type in this example  so we use this keyword before the type.  
  4.    public static int CountAlphabets(this string inputstring)   
  5.    {  
  6.       return inputstring.Replace(" ","").Length;  
  7.    }  
  8. }   
Step 3
 
Use the extention method by executing the below class
  1. class Test  
  2. {  
  3.    public static void Main()  
  4.    {  
  5.       string inputstring = "Zeko Das";  
  6.       int number= inputstring.CountAlphabets();  
  7.       Console.WriteLine(number);  
  8.       Console.ReadLine();  
  9.     }  
  10. }   
Note
Since inputstring is string type you will get the extension method in the VS intellisense.
 
Output
 
 
Happy Learning...