Is there a mechanism for the new c# 8 using
statement to work without a local variable?
Given ScopeSomething()
returns a IDisposable
(or null
)...
Previously:
using (ScopeSomething())
{
// ...
}
However in C# 8 with the using statement, it requires a variable name:
using var _ = ScopeSomething();
The _
here is not treated as a discard.
I would have expected this to have worked:
using ScopeSomething();
There are two kinds of resource_acquisition
supported by using
as per the specifications: local_variable_declaration
and expression
.
I believe the local using in C# 8 is a shortcut to local_variable_declaration
form not expression
form as per the language feature proposal, where you could see:
Restrictions around using declaration:
Must have an initializer for each declarator.
This also provides the ability to use more than one resources in a single using statement as per the language specs states:
When a
resource_acquisition
takes the form of alocal_variable_declaration
, it is possible to acquire multiple resources of a given type.
So you could do:
using IDisposable a = Foo1();
using IDisposable a = Foo1(), b = Foo2(), c = Foo3();
It may be possible that the language team could add expression
form support in the future versions, but for now, expression
is not yet supported.
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