Joey Joey - 10 months ago 94
C# Question

Parsing nameof expressions in Roslyn

I'm trying to do something with

expressions in a
, however, I noticed that there is no
in the AST. Instead I get an
for which
returns no matching symbols, and the expression of the invocation is an
containing an identifier token

So to recognize
expressions I would have added a special case to
, looking for whether
returns anything and if not, looking for whether the identifier is
. However, that sounds a bit iffy to me. Is there a better way maybe which shifts that sort of detection logic to the parser?

(P.S.: I know this is probably parsed like this for backwards compatibility reasons; just wondering whether there is an API for distinguishing
and normal invocations.)


I now indeed used the following snippet:

if (symbolInfo.Symbol == null &&
    symbolInfo.CandidateSymbols.IsEmpty &&
    symbolInfo.CandidateReason == CandidateReason.None) {
  var identifier = node.Expression as IdentifierNameSyntax;
  if (identifier != null && identifier.Identifier.Kind() == SyntaxKind.IdentifierToken && identifier.Identifier.Text == "nameof") {
    // We have a nameof expression

I opted not to exploit the constant value for detection just in case C# 8 or so adds yet a different operator in that vein, that might also have a constant value, but is not nameof. The detection pretty much detects exactly what the specification says is used for determining an invocation being a nameof expression:

Because nameof is not a reserved keyword, a nameof expression is always syntactically ambiguous with an invocation of the simple name nameof. For compatibility reasons, if a name lookup of the name nameof succeeds, the expression is treated as an invocation_expression – regardless of whether the invocation is legal. Otherwise it is a nameof_expression.