Extension Method In C#

What is Extension Method in C#?

Extension methods enable you to extend the functionality of existing type or class without changing source code of existing type or class.

When you want to add any new method in any existing class and you don’t want to make any change in source code of existing class or type then you should write extension method.

An extension method is a static method which is written in a static class. In an extension method we have to use this modifier with the first parameter. Here first parameter is the type/class to which which we are going to add extension method. If we need additional parameters then we can pass as per our requirement.

How to create Extension Method in C#?

To create an extension method we need to write a Static class and in that class we have to write a Static method having at least one parameter with "this" keyword. 

Currently there is no method available to add week in DateTime class. I am going to extend the functionality of DateTime class to add week with DateTime class.

  1. using System;  
  2. namespace ExtensionMethodDemo {  
  3.     static class DateTimeExtension {  
  4.         public static DateTime AddWeeks(this DateTime currentDate, int weeks) {  
  5.             return DateTime.Now.AddDays(weeks * 7);  
  6.         }  
  7.     }  
  8. }  

In the above example I have created an Extension method “AddWeeks”. Here I have extended functionality of DateTime class.

Now I am going to show that how we will use in our main program.

  1. using System;  
  2. namespace ExtensionMethodDemo {  
  3.     static class DateTimeExtension {  
  4.         public static DateTime AddWeeks(this DateTime currentDate, int weeks) {  
  5.             return DateTime.Now.AddDays(weeks * 7);  
  6.         }  
  7.     }  
  8.     class Program {  
  9.         static void Main(string[] args) {  
  10.             DateTime currentDate = DateTime.Now;  
  11.             Console.WriteLine("Current Date is {0}", currentDate);  
  12.             //Adding 1 week in currentDate  
  13.             currentDate = currentDate.AddWeeks(1);  
  14.             Console.WriteLine("Current Date after adding 1 week using extension method is {0}", currentDate);  
  15.             Console.Read();  
  16.         }  
  17.     }  
  18. }  

In the above example I have created a DateTime variable currentDate. Initially I have assigned current date and after that I am adding one week in this variable with help of AddWeeks extension method. When you will see extension method in Visual Studio intellisense extension word will be visible with down arrow. 

Output

Output of above program

Output

When to use Extension method

When you have to perform some operation with a particular type or class at multiple places in your project then rather than writing the same code at multiple places you should create an extension method and use it.

Ebook Download
View all
Learn
View all