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?
string magicString = nameof(magicString)
works bothers me more than the fact thatvar magicString = nameof(magicString)
doesn't work – Clowdefault(T)
and the assigns the result ofnameof()
. – Crinerstring magicString = nameof(magicString);
works without havingmagicString
defined beforehand – SchwabName
property to be found – Untraveledvar
works. – Grum