Roslyn: `var` variables cannot be used in `nameof` in the same line.

Created on 13 Jun 2020  路  4Comments  路  Source: dotnet/roslyn

class C
{
    static string M(string s)
    {
        var a = M(nameof(a)); // Error: a is not definitely assigned
        string b = M(nameof(b)); // Works fine.
    }
}
Area-Compilers Bug Concept-Diagnostic Clarity

Most helpful comment

Hmph. Alright, I might end up proposing something over at csharplang for this.

All 4 comments

        var a = M(nameof(a)); // Error: a is not definitely assigned
        string b = M(nameof(b)); // Works fine.

The second behavior (no errors) is the correct one right?

Yes, the second behavior is the correct behavior.

The compiler is behaving as specified. From https://github.com/dotnet/csharplang/blob/master/spec/statements.md#local-variable-declarations

In the context of a local variable declaration, the identifier var acts as a contextual keyword (Keywords).When the local_variable_type is specified as var and no type named var is in scope, the declaration is an implicitly typed local variable declaration, whose type is inferred from the type of the associated initializer expression. Implicitly typed local variable declarations are subject to the following restrictions:

  • The local_variable_declaration cannot include multiple local_variable_declarators.
  • The local_variable_declarator must include a local_variable_initializer.
  • The local_variable_initializer must be an expression.
  • The initializer expression must have a compile-time type.
  • The initializer expression cannot refer to the declared variable itself

[my emphasis]

While it is reasonable to expect that your example might work, it is currently required to be an error.

The specific diagnostic produced for this should be improved.

Hmph. Alright, I might end up proposing something over at csharplang for this.

Was this page helpful?
0 / 5 - 0 ratings