3.Hours() + 5.Minutes() + 30.Seconds()

Today I devised an interesting abuse of the C# extension methods.

Take a look at these three methods:

public static TimeSpan Hours(this int count)
{
    return TimeSpan.FromHours(count);
}
public static TimeSpan Minutes(this int count)
{
    return TimeSpan.FromMinutes(count);
}
public static TimeSpan Seconds(this int count)
{
    return TimeSpan.FromSeconds(count);
}

With these methods, one coud do this:

TimeSpan timespan = 3.Hours() + 5.Minutes() + 30.Seconds();

Not many people would categorize┬áthis as very readable or useful, but it’s an interesting way to make code read like English.

Continue reading