Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can you dispose of multiple objects within a Using block?

Tags:

c#

.net

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

like image 460
user20358 Avatar asked Sep 26 '12 13:09

user20358


2 Answers

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 
}   
like image 200
Mark Byers Avatar answered Nov 20 '22 19:11

Mark Byers


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.

like image 30
Tigran Avatar answered Nov 20 '22 18:11

Tigran