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();
}
}
Yes. You could clean it up a little like this
But you would still want a
usingfor each IDisposable object.Edit: Consider this example of not using an inner
usingstatement.Code
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
When execution leaves the block (actually, blocks), the compiled code executes calls to the Dispose() method of each object.