Rory Primrose

Learn from my mistakes, you don't have time to make them yourself

View project on GitHub

Nested using statements

Posted on November 9, 2006

The using statement in the .Net framework is a really good way of neatly using and disposing of an object in your code. It is certainly much more elegant than having Try/Catch/Finally blocks where you manually dispose of your objects. I do however have a minor issue with nested using statements. I can’t put my finger on it, but it just doesn’t seem that ‘right’ to me. Maybe it just looks ugly.

The following is an example taken from John Papa’s latest Data Points MSDN Magazine article:

using (TransactionScope ts = new TransactionScope())    
{
    using (SqlConnection cn2005 = new SqlConnection(cnString))
    {
        SqlCommand cmd = new SqlCommand(updateSql1, cn2005);
        cn2005.Open();
        cmd.ExecuteNonQuery();
    }
    
    ts.Complete();
}

As far as the messy look of it goes, I know that you can also do the following.

using (TransactionScope ts = new TransactionScope())
using (SqlConnection cn2005 = new SqlConnection(cnString))
{
    SqlCommand cmd = new SqlCommand(updateSql1, cn2005);
    cn2005.Open();
    cmd.ExecuteNonQuery();
}
    
ts.Complete();

I have some vague recollection that someone had a problem with this way of coding the using statement.

Has anyone come across any best practices with regard to nested using statements?