Welcome to AspAdvice Sign in | Join | Help

Orcs Goblins and .NET

I enjoy reading and writing. I hope you enjoy at least the former. I have moved my blog to Brendan.Enrick.com.

Syndication

Tags

News

Locations of visitors to this page

Navigation

Archives

Advice Sites

Articles

Blogs

Music

Nested Using Statements

I think it is a great idea to always be reading code. You may learn more than you intend to sometimes. Read an article to learn one trick and you may learn a completely different one. Earlier today I was reading some code written by Steve Smith. He wrote an extension method for the System.Web.UI.Control class called RenderControl. I was just looking to see what he had written, and from this little snippet of code I learned a cool trick.

 

public static string RenderControl(this System.Web.UI.Control control)
{
    StringBuilder sb = new StringBuilder();
    using (StringWriter sw = new StringWriter(sb))
    using (HtmlTextWriter textWriter = new HtmlTextWriter(sw))
    {
        control.RenderControl(textWriter);
    }
    return sb.ToString();
}

In the past I would have nested my using statements like this.

public static string RenderControl(this System.Web.UI.Control control)
{
    StringBuilder sb = new StringBuilder();
    using (StringWriter sw = new StringWriter(sb))
    {
        using (HtmlTextWriter textWriter = new HtmlTextWriter(sw))
        {
            control.RenderControl(textWriter);
        }
    }
    return sb.ToString();
}
So now I can go ahead and save myself some curly braces and extra indentation.

I enjoy all the little things one can learn from reader the code others write.

Published Thursday, August 28, 2008 2:50 PM by Brendan

Filed under: , ,

Comment Notification

If you would like to receive an email when updates are made to this post, please register here

Subscribe to this post's comments using RSS

Comments

No Comments

Leave a Comment

(required) 
required 
(required) 
Enter the code you see below