Possible duplicate:
Nested statements in C #
I am a big fan of using instructions in C #. I find this:
using (var foo = new ObjectWhichMustBeDisposed()) { other code }
... very readable than this:
var foo = new ObjectiWhichMustBeDisposed(); try { other code } finally { foo.Dispose(); }
This is not only more readable, but also prevents the random use of the foo variable after the using statement (i.e., after deleting it), whereas in the second example, foo could be used after it was placed.
One of the problems with using is that it leads to very nested code if many one-time objects are created. For instance:
using (var foo = new ObjectWhichMustBeDisposed()) { using (var bar = new ObjectWhichMustBeDisposed()) { other code } }
If both objects are of the same type, you can combine them into one using statement, for example:
using (var foo = new ObjectWhichMustBeDisposed(), bar = new ObjectWhichMustBeDisposed()) { other code }
However, if the objects are not of the same type, this will not work.
My question is whether a similar end can be achieved as follows:
using (var foo = new ObjectWhichMustBeDisposed()) using (var bar = new OtherObjectWhichMustBeDisposed()) { other code }
In this case, after the first use, there are no curly braces (and, therefore, there is no need to backtrack from the code). This compiles, and I assume that it works the same as an if without curly braces, i.e. It will use the following status (the second using in this case) as its "body".
Can anyone confirm if this is correct? (the description of the operator used does not help).