3

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?

David
  • 15,894
  • 22
  • 55
  • 66
Domas
  • 139
  • 3
  • 9
  • this might be helpful: http://stackoverflow.com/questions/1329739/nested-using-statements-in-c-sharp – bas Apr 21 '13 at 17:04

2 Answers2

4

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.

User 12345678
  • 7,714
  • 2
  • 28
  • 46
  • +1: Side note: there are cases when one can get away without multiple `using`: `StreamReader`/`StreamWriter` will in most cases dispose its associated stream when reader/writer is disposed. While such code would not lead to leaks it is much better/easier to read code when you have `using` for each `IDisposable` object. – Alexei Levenkov Apr 21 '13 at 17:04
  • The line you are going down with your answer is quite meta. Really its a case of how the IDisposable contract should work. Most people will agree that for all IDisposables, you should dispose of them as soon as you are "done" with them. In many cases that is when it goes out of scope. However in the case of Rx, IDisposables are used to control event handler lifetimes, so they should not be disposed straight away... Really depends on what the resource you are initialising is and when "finished using" happens... – Aron Apr 21 '13 at 17:06
1

You need both because they are completely independent, each one disposes its own variable. If you have multiple consecutive using statements you can also write them like this

using(SqlConnection con = new SqlConnection(...))
using(SqlCommand cmd = new SqlCommand(...))
{
   ...
}
nmat
  • 7,430
  • 6
  • 30
  • 43