Extension Methods: A simple example
If you've been developing software for any significant lenght of time, chances are you have compiled(for want of a better word) a repository of helper functions that have, over time, become valuable to you as you make your way through various applications. Extension Methods allow us to extend our custom and existing CLR types to include new functionality. These new functionality might already exist in the form of helper functions scattered throughtout our applications. For example, You might have a helper function that converts a string value to Proper Case. Extension methods allow us to "add" this ToProperCase() functionality to the primitive System.String type as if it were a built in method of the type.
In this post, I'll share with you a simple example of how I used extension methods to extend the sealed System.DateTime native type to include a
ToFriendlyDateString() method. Extension Methods are new in the .Net Framework 3.5.
you might want articles that were published one day ago to have their publish dates represented as "yesterday at 12:30 PM". Or if the article was publish today,
show the date as "Today, 3:33 PM".
The code snippet below shows the logic that will represent our extension method. Note the Namespace declaration, and the signature for the class definition. Note also the use of the this keyword when describing the input parameter for the ToFriendlyDateString() method. I'll eloberate on these later in this discussion.
namespace Utils
{
public static class Extensions
{
public static string ToFriendlyDateString(this DateTime Date)
{
string FormattedDate = "";
if (Date.Date == DateTime.Today)
{
FormattedDate = "Today";
}
else if (Date.Date == DateTime.Today.AddDays(-1))
{
FormattedDate = "Yesterday";
}
else if (Date.Date > DateTime.Today.AddDays(-6))
{
// *** Show the Day of the week
FormattedDate = Date.ToString("dddd").ToString();
}
else
{
FormattedDate = Date.ToString("MMMM dd, yyyy");
}
//append the time portion to the output
FormattedDate += " @ " + Date.ToString("t").ToLower();
return FormattedDate;
}
}
}
When creating extension methods, here are the rules
You must define a namespace for your class. Utils in the snippet above(Namespaces are not a strict requirement, but good practice nevertheless)- The class that contain the extension method must be decorated with the static modifier, and its visibility must be public
- The class must contain a static member, which will act as the extension method. This method must be public and must take one or more parameters, the first which must be a derivitive of the type you are extending. The first parameter definition must be preceeded by the this keyword
Extension methods are defined as static methods but are called by using instance method syntax. Their first parameter specifies which type the method operates on, and the parameter is preceded by the this modifier. Extension methods are only in scope when you explicitly import the namespace into your source code with a using directive. See example below showing how we might use the ToFriendlyDateString() method in our applications:
using Utils;
......
DateTime dt = new DateTime(2008, 2, 10, 8, 48, 20);Console.WriteLine(dt.ToFriendlyDateString());
For further details on Extension Methods, check out this MSDN link: http://msdn.microsoft.com/en-us/library/bb383977.aspx