Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using using to dispose of nested objects

If I have code with nested objects like this do I need to use the nested using statements to make sure that both the SQLCommand and the SQLConnection objects are disposed of properly like shown below or am I ok if the code that instantiates the SQLCommand is within the outer using statement.

using (var conn = new SqlConnection(sqlConnString))
{
    using (var cmd = new SqlCommand())
    {
        cmd.CommandType = CommandType.Text;
        cmd.CommandText = cmdTextHere;
        conn.Open();

        cmd.Connection = conn;
        rowsAffected = cmd.ExecuteNonQuery();
    }
}
like image 481
etoisarobot Avatar asked Apr 20 '10 18:04

etoisarobot


1 Answers

Yes. You could clean it up a little like this

using (SqlConnection conn = new SqlConnection(sqlConnString))
using (System.Data.SqlClient.SqlCommand cmd = new System.Data.SqlClient.SqlCommand())
{
   // code here
}

But you would still want a using for each IDisposable object.

Edit: Consider this example of not using an inner using statement.

class A : IDisposable
{
    public void Dispose()
    {
        Console.WriteLine("A Disposed");
    }
}

class B : IDisposable
{
    public void Dispose()
    {
        Console.WriteLine("B Disposed");
    }
}

Code

using (A a = new A())            
{
    B b = new B();
}

At the end of the block, A is properly disposed. What happens to B? Well, it's out of scope and simply waiting to be garbage collected. B.Dispose() is not called. On the other hand

using (A a = new A())
using (B b = new B())
{
}

When execution leaves the block (actually, blocks), the compiled code executes calls to the Dispose() method of each object.

like image 167
Anthony Pegram Avatar answered Oct 04 '22 01:10

Anthony Pegram