Extension methods are one of my favorite features of C# 3.0, they allow you to create new methods and plug them in classes already defined without having to derive them or even change it’s source code.
Everyone uses the DateTime class and a lot of those people have a class with handy methods to handle DateTime. Many of the handy methods would look better in the DateTime class but you can’t change it’s source code and you don’t want to derive from it and create a new DateTime class (of course). With extension methods you can plug these new methods in the DateTime class.
Let’s create a simple method named ’’‘DaysSince” that operates on two dates returning the number of days from one date to the other. The logic of the method is really simple:
public static class DateUtil
{
public static int DaysSince(DateTime d1, DateTime d2)
{
TimeSpan ts = d1.Subtract(d2);
return ts.Days;
}
}
You would use this class like this:
DateTime today = DateTime.Now;
DateTime pastDate = new DateTime(2008, 10, 9);
Console.WriteLine(DateUtil.DaysSince(today, pastDate);
My goal now is to be able to do this:
DateTime today = DateTime.Now;
DateTime pastDate = new DateTime(2008, 10, 9);
Console.WriteLine(today.DaysSince(pastDate));
To make this change just put a ’’‘this’’’ keyword in front of the first parameter of the static method. Now it should be like this:
public static class DateUtil
{
public static int DaysSince(this DateTime d1, DateTime d2)
{
TimeSpan ts = d1.Subtract(d2);
return ts.Days;
}
}
That is it, you can now make a call to the DaysSince method from any DateTime instance variable.
Here a the rules for creating a ExtensionMethod:
- Create a public static class (you call call it anything you want)
- Create the method you want as a public static method
- The first parameter of the method must always the a ’’‘this’’’ keyword followed by the class you want to plug the method to and the name of the parameter
- Whenever you want to use the extension method the ’’‘namespace’’’ in which the class is into must be referenced
If you want to create a method ’’‘WeeksAgo’’’ that let you get a new DateTime x weeks before the a certain date all you need to do is this:
public static class DateUtil
{
public static int DaysSince(this DateTime d1, DateTime d2)
{
TimeSpan ts = d1.Subtract(d2);
return ts.Days;
}
public static DateTime WeeksAgo(this DateTime d1, int numberOfWeeks)
{
DateTime newDate = d1.AddDays(-numberOfWeeks * 7);
return newDate;
}
}
And then you can use it like this:
Console.WriteLine(today.WeeksAgo(2).ToString());
Really cool addition to your utility belt, isn’t it?