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.
- string dateValue = "01-01-2017";
- DateTime reqdate;
- if (DateTime.TryParse(dateValue, out reqdate)) {
- return reqdate;
- } else {
- return DateTime.Now;
- }
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.
- public static class ProjectExtension {
- public static DateTime ToDateTime(this String dateTime) {
- DateTime reqdate;
- if (DateTime.TryParse(dateTime, out reqdate)) {
- return reqdate;
- } else {
- return DateTime.Now;
- }
- }
- }
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.
- String dateTime = "06-05-1987";
- dateTime.ToDateTime();
Note
We can use Extension methods on user defined classes as well.