"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

8/15/2010 4:03:06 PM #

Hey, I just found this article through Yahoo. I enjoy the briefing asserted by the article. I'm going to subscribe to your feeds aiming to like again. Please if you can drop in my blog, HackingEdge.com.

restaurant city cheat

8/16/2010 12:16:19 PM #

Thanks so much for your great website;this is the stuff that keeps me awake through out these day. I've been looking around for this site after being referred to them from a buddy and was pleased when I found it after searching for long time. Being a demanding blogger, I'm pleased to see others taking initivative and contributing to the community. Just wanted to comment to show my approval for your post as it's very interesting, and many writers do not get acknowledgment they deserve. I am sure I'll visit again and will spread the word to my friends.

restaurant city money hack 2010

8/23/2010 5:23:46 PM #

When I originally commented I clicked the "Notify me when new comments are added" checkbox and now each time a comment is added I get four emails with the same comment. Is there any way you can remove me from that service? Thanks

rockford help you sell

8/30/2010 11:41:13 PM #

Merely want to say your article is brilliant. The clarity in your post is simply impressive and i can assume you are an expert on this subject. Well with your permission allow me to grab your rss feed to keep up to date with forthcoming post. Thanks a million and please keep up the effective work.

Jinny

Add comment




biuquote
  • Comment
  • Preview
Loading



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