Search code examples
c#sqldisposeusing

Should I use several nested "using" stements?


I'm wondering whether I should use using statement inside another? For example:

using(SqlConnection con = new SqlConnection(...))
{
    ...
    using(SqlCommand cmd = new SqlCommand(...))
    {

    }
    ...
}

Are both "usings" necessary or would the first using dispose of everything when it's done?


Solution

  • You need to use a using statement for each object you want to dispose.

    I think that you will better understand this if you know that a using statement is mostly syntactic sugar, under the hood something like this is generated:

    myObject m = new myObjecyt()
    try
    {
       // Code here
    }
    finally
    {
       m.Dispose();
    }
    

    It might be desirable in your present context to dispose of every object contained within a single using block but in many other contexts, this behavior is not desirable.