C
C#3mo ago
zxa4fd

Can someone explain why these nested `using` is different from the ordinary one?

How is this:
using(resource1)
using(resource2)
{
// Code here
}
using(resource1)
using(resource2)
{
// Code here
}
different from:
using(resource1)
{
using(resource2)
{
// Code here
}
}
using(resource1)
{
using(resource2)
{
// Code here
}
}
5 Replies
Jimmacle
Jimmacle3mo ago
it's not
zxa4fd
zxa4fd3mo ago
I think they are. I remember that some streams were not behaving correctly if I don't use the second one. I think they have different scopes?
Jimmacle
Jimmacle3mo ago
the only change is no braces for the first using statement, which is fine as long as you only have one statement in it (which you do in this example, another using) it's the same rules for other statements like
if (thing1)
if (thing2)
DoThingIfThing1AndThing2AreTrue();
if (thing1)
if (thing2)
DoThingIfThing1AndThing2AreTrue();
reflectronic
reflectronic3mo ago
the reason you can do
using (resource1)
using (resource2)
using (resource1)
using (resource2)
is exactly for the same reason you can do
using (resource1)
// Code here
using (resource1)
// Code here
it is not special behavior, it is just that you can remove the braces for an embedded statement it works identically to the version with the braces
Jimmacle
Jimmacle3mo ago
not directly related but using declarations may be more convenient for you regardless unless you actually need to control the lifetime of the object within the method
using var thing = GetResource();
using var thing = GetResource();
will automatically dispose the object at the end of the scope it's declared in