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:
For using multiple objects of different types you can nest using the one-line syntax to save space: