Say you want to create a wrapper method to find the difference between two dates in days. You would probably create a static method that takes two dates and returns the difference. With the help of Extension methods, you can implement this feature directly into the DateTime structure.
See the code below:
namespace SeeSharpOverview.Version3
{
static class DateTimeExtender
{
public static int DifferenceInDays(this DateTime start, DateTime end)
{
return (end - start).Days;
}
}
}
Extension methods exist in static classes only. In addition, the static class should be non-generic.
Notice the this keyword used on the first parameter of DifferenceInDays. This means that the DateTime structure would be extended to include this method.
In order to use this extension method, I'd have to import the namespace SeeSharOverview.Version3. By importing the namespace, i could use all the extension methods existing inside that namespace.
using SeeSharpOverview.Version3;
DateTime date1 = DateTime.Now;
DateTime date2 = DateTime.Now.AddDays(2);
int days = date1.DifferenceInDays(date2);
System.Console.WriteLine(days);
The above code would output: 2, meaning difference in days is 2.
Extension Methods behave like normal static methods. Therefore, DateTimeExtender.DifferenceInDays(date1, date2) works just fine. Notice though, when using with the instance variable date1, the method takes only 1 argument.
Remember while implementing Extension Methods:
- A method M with the same signature to that of an Extension Method in a type has higher priority than the Extension Method. This mean, the method M will be called not the Extension Method.
General Guidelines to using Extension Methods:
- Should be used sparingly and only when needed
- Should not be preferred over inheritance , where inheritance is possible