0

i am currently using the Syntax API from Roslyn to generate some C# code and i am wondering about a small thing when defining a set accessor like this:

var setAccessor = AccessorDeclaration(SyntaxKind.SetAccessorDeclaration)
.AddBodyStatements(ExpressionStatement(InvocationExpression(IdentifierName("SetField"))
.AddArgumentListArguments(Argument(IdentifierName("value")))));
var propertyDeclaration = PropertyDeclaration(ParseTypeName("FieldType"), "Field")
                .AddModifiers(Token(SyntaxKind.PublicKeyword))
                .AddAccessorListAccessors(setAccessor);

which works perfectly fine. I am just a bit confused about the value keyword in the setAccessor, because normally i would expect to be able to declare it like this:

IdentifierName(Token(SyntaxKind.ValueKeyWord))

but as far as I can see there is no SyntaxKind.ValueKeyword, am I missing something or do I get something wrong here?

1 Answer 1

1

value is a special contextual keyword.

The contextual keyword value is used in the set accessor in property and indexer declarations. It is similar to an input parameter of a method.

The C# standard spec says:

The following identifiers have special meaning in the syntactic grammar, but they are not keywords: add (§17.7), alias (§16.3), get (§17.6.2), global (§16.7), partial (§17.1.4), remove (§17.7), set (§17.6.2), value (§17.6.2, §17.7.2), where (§25.7), and yield (§15.14). For convenience and clarity, these identifiers appear as terminals in the syntactic grammar; however, they are identifiers. [Note: As a result, unlike keywords, these identifiers can be written with a @ prefix and can contain unicode-escape-sequences. end note]

In other words, the syntax model treats all contextual keywords as identifiers, rather than as regular keywords. Some contextual keywords (like yield) do appear in SyntaxKind, but others (like var and value do not).

This github issue includes some relevant discussion, including this:

it is a contextual keyword, but not a keyword. Roslyn's syntactic model only contains explicit support for contextual keywords for which the context is syntactic. That is why the syntactic model doesn't tell you about the contextual keywords var and value. In any case all of the contextual keywords are identifiers.

This SO question is related.

Sign up to request clarification or add additional context in comments.

1 Comment

Ok thx, but I see this SyntaxKind.VarKeyword and also add , alias, get, global, partial, remove, set, where and yield have SyntaxKind entries. So to me it seems the only one missing in value or not?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.