"Using" Extension Methods in C#

by Matt 12. August 2009 11:08

Extension methods have become one of my favorite parts of C# as of late.  They can be very powerful and save you from writing some redundant code.  A great extension method I discovered a couple weeks ago was wrapping up the "using" statement like so:

public static void Use<T>(this T item, Action<T> action) where T : IDisposable
{
    using (item)
    {
        action(item);
    }
}

This allows you to write using statements using a Lambda expression like this:

void UseStream()
{
    string contents;

    new StreamReader(@"c:\file.txt").Use(s =>
        {
            contents = s.ReadToEnd();
        });

    // Do something with the contents
}

Instead of this:

void UseStream()
{
    string contents;

    using (StreamReader s = new StreamReader(@"c:\file.txt"))
    {
        contents = s.ReadToEnd();
    }

    // Do something with the contents
}

OK, so this really doesn't save you a lot of code, but it keeps you from writing a small amount of redundant code when instantiating what you are "using".  After about a week of using it, I modified it it to make it a little more powerful.  I created an additional extension method that looks like this:

public static TResult Use<T, TResult>(this T item, Func<T, TResult> action) where T : IDisposable
{
    using (item)
    {
        return action(item);
    }
}

This allows you to return a type from within your using statement very easily:

string ReturnStreamContents()
{
    return new StreamReader(@"c:\file.txt").Use(s =>
        {
            return s.ReadToEnd();
        });
}

Wrapping up a using statement this way could also allow you to perform any custom logic inside the extension method that you need to.

Comments are closed

Powered by BlogEngine.NET 1.5.0.7
Original Theme by Mads Kristensen | Modified by Crafty Coders