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.
- using System;
- namespace ExtensionMethodDemo {
- static class DateTimeExtension {
- public static DateTime AddWeeks(this DateTime currentDate, int weeks) {
- return DateTime.Now.AddDays(weeks * 7);
- }
- }
- }
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.
- using System;
- namespace ExtensionMethodDemo {
- static class DateTimeExtension {
- public static DateTime AddWeeks(this DateTime currentDate, int weeks) {
- return DateTime.Now.AddDays(weeks * 7);
- }
- }
- class Program {
- static void Main(string[] args) {
- DateTime currentDate = DateTime.Now;
- Console.WriteLine("Current Date is {0}", currentDate);
-
- currentDate = currentDate.AddWeeks(1);
- Console.WriteLine("Current Date after adding 1 week using extension method is {0}", currentDate);
- Console.Read();
- }
- }
- }
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 of above program
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.