Champion: Implicitly scoped using statement (16.3, Core 3) · Issue #114 · dotnet/csharplang (original) (raw)

See dotnet/roslyn#5881 and dotnet/roslyn#181

Motivation (TL;DR edition):

Allow using keyword to be used to declare a variable that will be disposed at the end of the current block. This avoids creating a new block with an additional level of indentation:

Before:

public void Foo() { using (var connection = new SqlConnection(connectionString)) { connection.Open(); using (var command = connection.CreateCommand()) { command.CommandText = "SELECT FOO FROM BAR"; using (var reader = command.ExecuteReader()) { while (reader.Read()) { ProcessRecord(reader); } } } } }

After:

public void Foo() { using var connection = new SqlConnection(connectionString)); connection.Open(); using var command = connection.CreateCommand()); command.CommandText = "SELECT FOO FROM BAR"; using var reader = command.ExecuteReader()); while (reader.Read()) { ProcessRecord(reader); } }

As an implementation detail, the variables would be disposed in the reverse order in which they are declared. So given the above code, the order in which the resources would be disposed is reader, command and then connection.