nameof operator has gone through five iterations as the Roslyn team worked to nail down its syntax and semantics. Now that the design of the
nameof operator has been finalized, we can look at some simple examples.
nameof is a contextual keyword. This means there is no way to distinguish the
nameof keyword from a call to a method that happens to be named
Lucian Wischik elaborates:
In C#, nameof is stored in a normal InvocationExpressionSyntax node with a single argument. That is because in C# ‘nameof’ is a contextual keyword, which will only become the “nameof” operator if it doesn’t already bind to a programmatic symbol named “nameof”
This means we can only identify
nameof expressions at the semantic level. We do so by finding all invocations to “nameof” that do not bind to any symbol. These invocations must also be standalone (ie. not part of a member access like
As with all contextual keywords, it’s a bit of a pain to work with. But that’s the price we pay for backwards compatability.
Previous versions of the Roslyn API allowed for direct creation of a
NameOfExpressionSyntax. Now we must create an
InvocationExpressionSyntax with the identifer “nameof”.
For example, we can generate the following nameof expression:
string result = nameof(result);
The important takeaway is that (at the syntax level)
nameof expressions are no different than regular invocations.