27

How to take care of multiple objects getting disposed off in a Using statement?

Sample code

using(MyClass obj = new MyClass())
{
    MyOtherClass objOC= new MyOtherClass()
    TextReader objTR = new StringReader(...);  
    // other code
}

MyClass obj will be be disposed at the end of the Using block, but then what about MyOtherClass objOC and TextReader objTR. As far as I know it they wont get disposed, so should I be having a nested Using block there, like this below? I will need a real wide screen monitor if the number of objects increase

Is this below correct?

using(MyClass obj = new MyClass())
{
    using (MyOtherClass objOC= new MyOtherClass())
    {
        using (TextReader objTR = new StringReader(...))
        {
           //code using all three objects 
        }   
    } 
    // other code using just `MyClass obj`
}

MyClass & MyOtherClass both implement IDisposable

rekire
  • 47,260
  • 30
  • 167
  • 264
user20358
  • 14,182
  • 36
  • 114
  • 186
  • 1
    related: [Nested using statements in C#](http://stackoverflow.com/questions/1329739/nested-using-statements-in-c-sharp) – Paolo Moretti Sep 26 '12 at 13:47

2 Answers2

60

Yes, your code is correct. Here's a couple other things you might want to be aware of...

You can declare multiple objects of the same type in a single using statement. From the documentation:

using (Font font3 = new Font("Arial", 10.0f), 
            font4 = new Font("Arial", 10.0f))
{
    // Use font3 and font4.
}

For using multiple objects of different types you can nest using the one-line syntax to save space:

using (MyClass obj = new MyClass())
using (MyOtherClass objOC= new MyOtherClass())
using (TextReader objTR = new StringReader(...))
{
    // code using all three objects 
}   
Mark Byers
  • 811,555
  • 193
  • 1,581
  • 1,452
2

Yes, if you want to gurantee the Dispose(..) call on all of them you have to enclose them inside using statment like in second example.

Or you can declare multiple objects inside single using statement. It's a matter of coding style and code flow.

Tigran
  • 61,654
  • 8
  • 86
  • 123