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
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
}
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.
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