Yes, absolutely. The details are in section 8.13. There isn't a concise statement of your exact question, but:
A using statement of the form
using (expression) statement
has the same three possible expansions, but in this case ResourceType
is implicitly the compile-time type of the expression, and the resource variable is inaccessible in, and invisible to, the embedded statement.
The "three possible expansions" referred to cover the more common case of declaring a variable at the same time. Basically the important thing is that it behaves the same way, aside from the variable's scope. Dispose
will still be called - otherwise there'd be no point in putting in a using
statement at all :)
Note that the two aren't quite equivalent in terms of what's valid within the block, because a variable declared by the using
statement is readonly. So this is valid:
// Warning but no error
MemoryStream ms = new MemoryStream();
using (ms)
{
ms = null;
}
but this isn't:
using (MemoryStream ms = new MemoryStream())
{
// error CS1656: Cannot assign to 'ms' because it is a 'using variable'
ms = null;
}
Note that even in the case where it's valid, it's the original value of ms
which is used for disposal. The compiler makes this clear:
warning CS0728: Possibly incorrect assignment to local 'ms' which is the argument to a using or lock statement. The Dispose call or unlocking will happen on the original value of the local.
Note that this form doesn't generate a warning:
// No warning
MemoryStream ms;
using (ms = new MemoryStream())
{
ms = null;
}
On the other hand, aside from that, they really will behave in the same way.
EDIT: As bzlm notes, the fact that the variable remains in scope after the using
statement means it's usually not a good idea. However, objects which have been disposed aren't always unusable. For example:
MemoryStream ms = new MemoryStream();
using (ms)
{
// Do stuff
}
byte[] data = ms.ToArray();
That will work just fine - the MemoryStream
keeps the data even when it's disposed. It still feels somewhat wrong to me though.