C # 7.0 discard parameter ambiguity

From https://blogs.msdn.microsoft.com/dotnet/2017/03/09/new-features-in-c-7-0/ :

We also allow to "strip" output parameters as _ so that you can ignore parameters you don't need:

p.GetCoordinates(out var x, out _); // I only care about x

      


Consider the following code:

void Foo(out int i1, out int i2)
{
    i1 = 1;
    i2 = 2;
}

int _;
Foo(out var _, out _);
Console.WriteLine(_); // outputs 2

      


Questions:

Why is the "discard" option displayed in this context?

Also, there should be no "already defined in scope" error for out var _

?

int i;
Foo(out var i, out i);
Console.WriteLine(i); // Error: A local variable or function named 'i'
                      // is already defined in this scope

      

+3


source to share


1 answer


Here's a GitHub issue that describes the behavior of the discards , relevant parts:

However, semantically we want this to create an anonymous variable and shadow any true variable (such as a parameter or field) from the enclosing scope named _.
...
We must be careful with these changes so that any program that uses _ as an identifier and is legal today continues to compile with the same value under these revised rules.

_

means "discard this parameter" if you declare it and use it

  • as an identifier in a "notation" (declaration expression) that includes parameters out

    and deconstruction of tuples and similar
  • as an identifier according to the pattern ( switch

    ... case int _

    )
  • obviously also for declaring anonymous delegates that must take parameters to match the type of the delegate, but where you don't need the actual parameter.


out var _

is one of them in this category.

However int _;

, it is a separate statement, and thus it means that you "care" about this variable and therefore do not discard.

Thus, you get a normal variable with the name _

, which is still legal . This gets the value 2 from the method call, as expected.

+8


source







All Articles