Learn About Extension Methods In C#

What are extension methods in C#?

An Extension method is a technique to add custom methods to the existing classes where we cannot edit them. For example, we are using one class from another project where we don’t have permission to edit it. But, we have to add a method to that class to serve our purpose. Here, we can make use of Extension methods.

Situation

We have got a requirement in our project to convert the string value to DateTime and we have to use this in several places in our project. So, we have to write the following code every time whenever we need to convert.

  1. string dateValue = "01-01-2017";  
  2. DateTime reqdate;  
  3. if (DateTime.TryParse(dateValue, out reqdate)) {  
  4.     return reqdate;  
  5. else {  
  6.     return DateTime.Now;  
  7. }  

Alternate solution

Instead of writing everywhere, we can create a public method and can access it by creating the object to its class. But, we need to create the object of the class every time. So, here comes our extension method implementation.

Actual solution

Create an extension method for the existing String class and use it wherever you want it.

Let’s see how to implement it and use it.

How to implement Extension method

We have to create an extension method with the help of a static method, as follows. It is better to create a separate static class because we can add all the required extension methods in this class. 

  1. public static class ProjectExtension {  
  2.     public static DateTime ToDateTime(this String dateTime) {  
  3.         DateTime reqdate;  
  4.         if (DateTime.TryParse(dateTime, out reqdate)) {  
  5.             return reqdate;  
  6.         } else {  
  7.             return DateTime.Now;  
  8.         }  
  9.     }  
  10. }  

We have created our extension method to return the datetime from the string value.

How to use it

Simply create a String type and check its available methods. You will see the ToDateTime method available for it to convert the string to DateTime type.

C#

  1. String dateTime = "06-05-1987";  
  2. dateTime.ToDateTime();  

Note

We can use Extension methods on user defined classes as well.

Next Recommended Reading Extension methods in C# 3.0