The CSharpSyntaxWalker
class is out of the box implementation of the Visitor pattern, that we can use to traverse our Syntax Tree. Here is a simple example of a Syntax Walker that collects all the struct
-s that have a name, starting with the letter A
:
public class StructCollector : CSharpSyntaxWalker
{
public StructCollector()
{
this.Structs = new List<StructDeclarationSyntax>();
}
public IList<StructDeclarationSyntax> Structs { get; }
public override void VisitStructDeclaration(StructDeclarationSyntax node)
{
if (node.Identifier.ToString().StartsWith("A"))
{
this.Structs.Add(node);
}
}
}
We can use our SyntaxWalker in the following way:
var structCollector = new StructCollector();
structCollector.Visit(syntaxRoot); // Or any other syntax node
Console.WriteLine($"The number of structs that have a name starting with the letter 'A' is {structCollector.Structs.Count}");