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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With