Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 813
Domas Avatar asked Mar 07 '26 01:03

Domas


1 Answers

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.

like image 200
User 12345678 Avatar answered Mar 09 '26 14:03

User 12345678



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!