Extension Method in C#

Extension methods were introduced in C# (3.0). By using extension methods we can add methods to existing types with new functionality without the need of creating new derived types.

There are a few things to remember while creating an extension method,

  • The extension method should be a static method.
  • Since it is a static method it should be in a static class.
  • this” keyword is used as a parameter in the extension method.

All these of three conditions should be met to create an extension method. The extension method created is visible in the C# intellisense.

Let us see an example of the extension method. Write the following code in the Program.cs.

  1. public static class ExtensionMethod  
  2. {  
  3.     public static string ConvertTexttoUppercase(this string text)  
  4.     {  
  5.         return text.ToUpper();  
  6.     }  
  7. }  
  8. class Program  
  9. {  
  10.     static void Main(string[] args)  
  11.     {  
  12.         string text = "welcome to .net snippets!!";  
  13.         text = text.ConvertTexttoUppercase();  
  14.         Console.WriteLine(text);  
  15.         Console.ReadLine();  
  16.     }  
  17. }  
In the preceding example we have a static class “ExtensionMethod”. This class has a static function that accepts a parameter having “this” keyword. We can now use this function on a string, since we have defined the parameter as a string.

In the example we have a string with some text assigned. Our requirement is to convert the string to uppercase. So we have used this extension method on the string. When we write text and press dot we get the method in the intelligence on the string object. Refer to the following image.



When the program has run we get the following output.



Just to make sure this keyword is important for extension method to work, let us remove the “this” keyword” and check what happens. Remove the keyword and build the program. We get the below error in the program.



So it is important to use the “this” keyword as a parameter.

 

Ebook Download
View all
Learn
View all