Possible Duplicate:
Nested using statements in C#
I'm a big fan of the using
statement in C#. I find this:
using (var foo = new ObjectWhichMustBeDisposed())
{
other code
}
...very much more readable than this:
var foo = new ObjectiWhichMustBeDisposed();
try
{
other code
}
finally
{
foo.Dispose();
}
Not only is it more readable, it also prevents accidental use of the foo
variable after the using
statement (i.e. after it has been disposed), whereas in the second example foo
could be used after it had been disposed.
One problem with using
, though, is that it tends to lead to very nested code if lots of disposable objects are being created. For example:
using (var foo = new ObjectWhichMustBeDisposed())
{
using (var bar = new ObjectWhichMustBeDisposed())
{
other code
}
}
If both the objects are of the same type, then you can combine them into a single using
statement, like so:
using (var foo = new ObjectWhichMustBeDisposed(),
bar = new ObjectWhichMustBeDisposed())
{
other code
}
However, if the objects are not of the same type, then this will not work.
My question is whether it is OK to to achieve a similar end like this:
using (var foo = new ObjectWhichMustBeDisposed())
using (var bar = new OtherObjectWhichMustBeDisposed())
{
other code
}
In this case, there are no curly-braces after the first using (and hence no need to indent the code). This compiles, and I assume that this works just like an if
statement with no braces - i.e. it'll use the next statment (the second using
in this case) as its "body".
Can anyone confirm whether that's correct? (The description of the using statement is no help).
Yes the code you propose
using (var foo = new ObjectWhichMustBeDisposed())
using (var bar = new OtherObjectWhichMustBeDisposed())
{
other code
}
is both OK and quite common.
You do not need to use additional { } after each using (other than the one that contains other code, if other code is more than one statement) because each using has exactly one statement following it.
using (var foo = new ObjectWhichMustBeDisposed())
using (var bar = new OtherObjectWhichMustBeDisposed())
using (var baz = new OtherObjectWhichMustBeDisposed())
using (var quux = new OtherObjectWhichMustBeDisposed())
{
other code
}
would also be fine.
Look at using
statement definition in C# standard:
12.3.3.17 Using statements
For a using statement stmt of the form:
using ( resource-acquisition ) embedded-statement
embedded-statement is whatever from the following (See Item A2.5):
embedded-statement:
block
empty-statement
expression-statement
selection-statement
iteration-statement
jump-statement
try-statement
checked-statement
unchecked-statement
lock-statement
using-statement
yield-statement
So both usages of using
(block or another using-statement) are absolutely equivalent from C# Standard point of view.
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