Language Extensions and Lambdas

Like everyone, I create little snippets of code to help me accomplish some programming task.

I found myself writing “stopwatch” code way too much. So, in my shared library that I use at home, I added this little static method that times how long code takes to run, and then returns a timespan:

/// <summary>

/// Times how long <paramref name=”code”/>

/// takes to run.

/// </summary>

/// <param name=”code”>An anonymous method or

/// <see cref=”Action”/> delegate that should

/// be run.</param>

/// <exception cref=”ArgumentNullException”>

/// When <paramref name=”code”/> is null.</exception>

public static TimeSpan TimeIt(Action code)

{

    if (code == null)

        throw new ArgumentNullException(“code”);


    Stopwatch stopwatch = Stopwatch.StartNew();


    // Run the code that was pass in.

    code.Invoke();

    stopwatch.Stop();


    return stopwatch.Elapsed;

}

I can now use that very easily anywhere I want to time something. The problem is, it returns a TimeSpan, and so more code is needed to output it somewhere. So, I created some extension methods for TimeSpan. These could be more well-thought out, but these will work for now:

public static class TimeSpanExtensions

{

    public static void ToDebug(this TimeSpan timespan, String message)

    {

        Debug.WriteLine(timespan.ToString() + ” – “ + message);

    }
    public static void ToConsole(this TimeSpan timespan, String message)
    {
        Console.WriteLine(timespan.ToString() + ” – “ + message);
    }
    public static void ToMessageBox(this TimeSpan timespan, String message)
    {
        MessageBox.Show(timespan.ToString() + ” – “ + message);
    }
}

This mean that in code, I can now do something like this:

TimeIt(() =>

{

    for (int index = 0; index < 10000000; index++)

    {

    }

}).ToDebug(“Counted to 1 million.”);

And it creates output like this:

00:00:00.0455012 – Counted to 1 million.

As I’m learning and playing around more with .NET 4.0 and beyond, I really like and agree with the direction it’s going. The technology is becoming easier and easier to use. I like it!

Posted in .NET 4.0, Uncategorized

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Archives
Categories

Enter your email address to follow this blog and receive notifications of new posts by email.

Join 2 other followers

%d bloggers like this: