Nov 10 2006

Nested using statements

Category: IT Related | .NetRory Primrose @ 04:21

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?

Tags:

Comments

1.
Nick Nick says:

Urgh, silly Captcha requiremen for comments (normally Community Server allows cross-posting on comments).  Anyhow I was just adding my 2c worth re VB.NET and other compilers around the using statement

2.
Nate Nate says:

I've never seen any better way to do this and it really bothers me too

Add comment


(Will show your Gravatar icon)

  Country flag

biuquote
  • Comment
  • Preview
Loading