Search code examples
c#c#-6.0nameof

Implicit and explicit typing with C# 6 nameof


One of the handiest new features in C# 6 is nameof, which allows the programmer to effectively eliminate the use of magic strings.

Per the documentation, nameof returns a string:

Used to obtain the simple (unqualified) string name of a variable, type, or member.

That works just fine with explicit typing in the following code example:

string magicString = nameof(magicString);

However, when using implicit typing with the var keyword:

var magicString = nameof(magicString);

the compiler throws an error:

Cannot use local variable 'magicString' before it is declared

I then did some more experimenting with the C# Interactive window available in Visual Studio. Again, the first example worked fine, but the second example threw a different error this time:

error CS7019: Type of 'magicString' cannot be inferred since its initializer directly or indirectly refers to the definition.

The nameof expression clearly returns a string, so why can't the compiler implicitly type it when being used with the initialized variable?


Solution

  • The language team felt that this wasn't worth the spec complexity.

    You can see the discussion here.

    The underlying reason for this behavior is that the spec says (§8.5.1) names declared with var aren't visible in the declaring statement, since before nameof, there was no way in which that could be valid.

    Implicitly typed local variable declarations are subject to the following restrictions:

    • ...
    • The initializer expression cannot refer to the declared variable itself

    Without var, statements like int x = x = 1; or int x = 1, y = x; are legal; with var, nothing in that form is valid.