I'm trying to do something with nameof
expressions in a CSharpSyntaxWalker
, however, I noticed that there is no NameOfExpressionSyntax
in the AST. Instead I get an InvocationExpressionSyntax
for which SemanticModel.GetSymbolInfo
returns no matching symbols, and the expression of the invocation is an IdentifierNameSyntax
containing an identifier token "nameof"
.
So to recognize nameof
expressions I would have added a special case to VisitInvocationExpression
, looking for whether GetSymbolInfo
returns anything and if not, looking for whether the identifier is nameof
. 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 nameof
and normal invocations.)
nameof
expressions are compile-time constant. You can use that fact to distinguish it from normal invocations. You can call SematicModel.GetConstantValue()
on the InvocationExpressionSyntax
. In case it's a nameof
, you get back the string / name inside the Optional<object>.Value
(HasValue
also returns true).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With