Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

using statement in C# 8 without a variable

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();
like image 855
Daniel A. White Avatar asked Apr 11 '20 02:04

Daniel A. White


1 Answers

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 a local_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.

like image 50
weichch Avatar answered Oct 09 '22 02:10

weichch