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.

I think it’s better (albeit not shorter) than:

TimeSpan timespan = new TimeSpan(3, 5, 30);

because it reads almost as English, but it’s perhaps not better than this (now, the numbers are explained):

TimeSpan timespan = new TimeSpan(hours: 3, minutes: 5, seconds: 30);

Another example where this might be useful for readability is the following:
Instead of

DateTime threeHoursAgo = DateTime.Now.AddHours(-3); 


DateTime threeHoursAgo = DateTime.Now.Subtract(TimeSpan.FromHours(3));

you’d write this:

DateTime threeHoursAgo = DateTime.Now - 3.Hours();

AddHours method is somewhat counter-intuitive for negative argument, because the Add word is used for subtracting (even though it’s mathematically sound).
The other example is too verbose: .Subtract(TimeSpan.From instead of a single subtraction (-) operator.

This post doesn’t have a lesson to learn. It just shows an interesting idea. However, I would like to know if you would ever use such constructs in your code, and if not, why not? If you have anything to add (or subtract), please comment below.

Leave a Reply

Your email address will not be published. Required fields are marked *