Click here to Skip to main content
12,758,605 members (31,357 online)
Click here to Skip to main content
Add your own
alternative version

Tagged as


3 bookmarked
Posted 1 Oct 2012

Simple extension methods for code readability

, 2 Oct 2012 CPOL
Rate this:
Please Sign up or sign in to vote.
Make your code more readable by using these methods related to Timespan management


Whenever you deal with Timers, Timeouts, or anything which involves calculation on dates you will end up dealing with the TimeSpan class.

I don't find particularly readable to write the following code : 

// a 5 hours lapse of time
var theTimespan = new TimeSpan(0, 5, 0, 0, 0);

and find much more easy to read this one:

// a 5 hours lapse of time
var theTimespan = 5.Hours();

Extension methods 

Use these methods (which extends the int class) to create TimeSpan the easy and readable way. 

public static TimeSpan Days(this int value)
    return new TimeSpan(value, 0, 0, 0, 0);

public static TimeSpan Years(this int value)
    var dt = DateTime.Now.AddYears(value);
    return (dt - DateTime.Now).Duration();

public static TimeSpan Hours(this int value)
    return new TimeSpan(0, value, 0, 0, 0);

public static TimeSpan Minutes(this int value)
    return new TimeSpan(0, 0, value, 0, 0);

public static TimeSpan Seconds(this int value)
    return new TimeSpan(0, 0, 0, value, 0);

public static TimeSpan Milliseconds(this int value)
    return new TimeSpan(0, 0, 0, 0, value);


This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


About the Author

New Zealand New Zealand
No Biography provided

You may also be interested in...


Comments and Discussions

QuestionNot really more readable Pin
suq madiq3-Oct-12 11:23
membersuq madiq3-Oct-12 11:23 
This isn't really any more readable than the built in syntax. In fact, I'd argue it is less readable since you can't tell what the Hours method returns without explicitly typing it (not using var) or looking up the method's return type by hovering or viewing the definition.

var theTimespan = 5.Hours();

var theTimespan = TimeSpan.FromHours(5);

At least here, the API implies FromHours returns a type of TimeSpan. Also, methods on numbers and strings (instead of variables or objects) make me cringe and should be discouraged. You could at least do something like:

int hours = 5;
TimeSpan theTimespan = hours.Hours();

modified 3-Oct-12 17:14pm.

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

Permalink | Advertise | Privacy | Terms of Use | Mobile
Web02 | 2.8.170217.1 | Last Updated 2 Oct 2012
Article Copyright 2012 by Guirec
Everything else Copyright © CodeProject, 1999-2017
Layout: fixed | fluid