Friday, May 27, 2011

Simpler TimeSpan construction

The TimeSpan structure in .NET is useful when you need to represent an interval of time. It has three different constructors that take varying degrees of days, hours, minutes, seconds and milliseconds to initialize the TimeSpan. This is great for its flexibility but all to often you just want a TimeSpan based on one value (like minutes or seconds) and all of the other values are zero. I've seen code like this to sleep a Thread for 10 seconds:
Thread.Sleep(new TimeSpan(0, 0, 0, 10, 0));

Thankfully there are a number of static convenience functions that take the single value and return a TimeSpan. They are all in form of FromX(double) where X maps to the same days, hours, minutes, seconds and milliseconds as above. So instead of the code above we can write:
Thread.Sleep(new TimeSpan.FromSeconds(10));

Nothing Earth shattering but just a little bit clearer for the next person who reads the code.

No comments: