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

Climb the curve

I’ve recently had a project in which an interesting challenge popped up.

Write a function that will round a timestamp to the closest 15min value.

Something like this:


Additional example:

For May 1 2015, 18:44:20.000 – round to May 1 2015, 18:45:00.
For May 1 2015, 18:07:30.000 – round to May 1 2015, 18:00:00.
For May 1 2015, 23:52:30.001 – round to May 2 2015, 00:00:00.

For this discussion, let’s allow the mid-points to be rounded to any (of the two) neighbouring 15min timestamps. The problem seems easy. And it is. But something strange happened.

I asked this question several people around the workplace. They were able to start with a sound idea in seconds (well, most of them). The thing that shocked me is that no two persons proposed the same solution. Every one of them had his own way.

So here are few of the first ideas:

Continue reading