Both classes for practicality sake are disposable.
I understand what a using block does. But I'm not sure of all of the ways it can or needs to be used.
For example is this correct?
using (MyClass myClass = new MyClass(params))
{
myClass.name = "Steve";
SecondClass myClassSecond = new SecondClass(params);
myClassSecond.name = "George";
myClassSecond.msg = "Hello Man in the Yellow Hat";
}
Are both classes above disposed of?
Or do I need both inside a using statement?
using (MyClass myClass = new MyClass(params))
{
myClass.name = "Steve";
using (SecondClass myClassSecond = new SecondClass(params))
{
myClassSecond.name = "George";
myClassSecond.msg = "Hello Man in the Yellow Hat";
}
}
Is the above correct, or is there a better way to use multiple using statements?
Your second example is proper assuming SecondClass is indeed dispoable. If it is the first example is not correct as mySecondClass will not be disposed of. If a block of code controls the lifetime of a disposable instance it should always dispose of it.
FYI I prefer this style for disposing multiple objects in the same block as I find it more readable.
Both
usings
share the same scope and Dispose in reverse order of declaration.A using block does not automatically dispose any child objects that implement
IDisposable
. You have to wrap inner disposables in using blocks if you want them disposed. You do, however, have a few different options for this.You could nest multiple using blocks and they are evaluated inner-most to outer-most. There is a better way to do this, but the following example works:
If the declarations are consecutive and you don't need to do anything in between, the following syntax is more succinct:
If you need to do something in between the declarations, then your latter example is correct:
My rule of thumb is...if it implements idisposable, I use a using block.
Always better safe than sorry.
To answer your question, I would go with the second option.