Wednesday, 12 September 2007

C# 3.0 Basic - Extension methods

Alex's example on extension method as a whole was really cool. I will ask him for it later. Meanwhile I will write a super simplified one to show that I understand what he was saying.:D

First here are two extension methods. The first one, Hours, extends int type; and the second one, FromNow, extends TimeSpan type.
public static TimeSpan Hours(this int i)
{
return new TimeSpan(0, i, 0, 0);
}

public static DateTime FromNow(this TimeSpan t)
{
return DateTime.Now.Add(t);
}

So I can write something like this:
DateTime ThreeHoursFromNow = 3.Hours().FromNow();

Probably my example cannot illustrate the power of extension methods, but well, you get the idea. :)

No comments:

Post a Comment