So I'm beginning to look into the new c# language features coming with Orcas, and probably the simplest is Extension Methods. Below is some code I have migrated to 3.0 to convert unix timestamps to proper DateTime objects.
public static class MyExtensions
{
private static DateTime _baseDate = new DateTime(1970, 1, 1);
public static DateTime ConvertUnixTimestampToDateTime(
this double secondsAfter1970)
{
if (secondsAfter1970 == double.NaN)
throw new ArgumentOutOfRangeException(
"Number of seconds since Jan 1, 1970 required");
return _baseDate.AddSeconds(secondsAfter1970);
}
}
So what is going on here? There are only 2 things to notice.
- This is a static class, which means everything in the class must likewise be static. I'll explain why this restriction exists shortly.
- The "this" in the method signature indicates that this method may be used to extend the double class.
From there, you may simply call the method on any double value as if it had been there all along.
static void Main(string[] args)
{
double oneWeek = 60 * 60 * 24 * 7;
Console.WriteLine("Called as Extension Method: " +
oneWeek.ConvertUnixTimestampToDateTime()
.ToShortDateString());
Console.WriteLine("Called as Static Method: " +
MyExtensions.ConvertUnixTimestampToDateTime(oneWeek)
.ToShortDateString());
Console.ReadLine();
}
The output:
Notice that I can still call this method as I would any other static method. The only difference is that now I can use it from instances of the double class as well.
So how is this functionality provided? The compiler simply replaces your extension method invocation with the static method when it compiles your code. As a result, there is no difference in how the two calls are made.
Also of note, is that you must create a using statement for your extensions class if it is located in a different namespace. No surprise here, you have to follow the same rules that you would have used to call the static method in .net 2.0.
To be honest, I haven't quite decided what I think of extension methods just yet. I think they'll be pretty benign, but a friend of mine who is a killer developer in his own right is concerned that the "this" keyword is a little too easy to miss. I can certainly see his point. Hopefully the way you organize these methods, or the static classes you enclose them with, will provide enough context. Regardless, there's nothing earth shattering here, just some new syntactic sugar.