Click here to Skip to main content
15,881,803 members
Articles / Programming Languages / C#
Tip/Trick

Simple extension methods for code readability

Rate me:
Please Sign up or sign in to vote.
4.89/5 (6 votes)
2 Oct 2012CPOL 16.6K   5   3
Make your code more readable by using these methods related to Timespan management

Introduction

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 : 

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

and find much more easy to read this one:

C#
// 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. 

C#
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);
}

License

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


Written By
Architect
Switzerland Switzerland
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
QuestionNot really more readable Pin
suq madiq3-Oct-12 10:23
suq madiq3-Oct-12 10:23 
Questionit's cool Pin
Marius Bancila2-Oct-12 5:13
professionalMarius Bancila2-Oct-12 5:13 
that you can actually write things like:

C#
var tspan = 5.Hours() + 4.Minutes() + 2.Seconds();

SuggestionDateTime.Now issue. Pin
Andrew Rissing2-Oct-12 4:31
Andrew Rissing2-Oct-12 4:31 

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.