It's hard for me to define contextual keywords (var, yield, async, etc.) with Roslyn. I inherited from CSharpSyntaxWalkerand overrode VisitToken. SyntaxTokenprovides an extension method IsContextualKeyword(), but it always returns false.
Here is a sample that should display all contextual keywords in the syntax tree:
public class TokenWalker : CSharpSyntaxWalker
{
public TokenWalker() : base(SyntaxWalkerDepth.Token) { }
public override void VisitToken(SyntaxToken token)
{
if (token.IsContextualKeyword())
{
Console.WriteLine(token.ToString());
}
base.VisitToken(token);
}
}
And using this class as follows:
public static void TaggingVarKeyword()
{
var tree = CSharpSyntaxTree.ParseText(@"
public class MyClass
{
public void MyMethod()
{
var var = 4;
}
}
");
var walker = new TokenWalker();
walker.Visit(tree.GetRoot());
}
I would expect exit from "var", but I do not get output at all.
If I put a breakpoint at VisitToken(), I see that var is passed as IdentifierTokennot a TypeVarKeyword.
Can contextual keywords be defined at a purely syntactic level? If so, do you know how I can do this?