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.

Comments