Syntax tree C# with Example



Syntax tree C# with Example

A Syntax Tree is an immutable data structure representing the program as a tree of names, commands and marks 
(as previously configured in the editor.) 
For example, assume a Microsoft.CodeAnalysis.Compilation instance named compilation has been configured. 
 

There are multiple ways to list the names of every variable declared in the loaded code. To do so naively, take all 
pieces of syntax in every document (the DescendantNodes method) and use Linq to select nodes that describe 
variable declaration: 
foreach (var syntaxTree in compilation.SyntaxTrees) 
{ 
var root = await syntaxTree.GetRootAsync(); 
var declaredIdentifiers = root.DescendantNodes() 
.Where(an => an is VariableDeclaratorSyntax) 
.Cast() 
.Select(vd => vd.Identifier); 
foreach (var di in declaredIdentifiers) 
{ 
Console.WriteLine(di); 
} 
} 
Every type of C# construct with a corresponding type will exist in the syntax tree. To quickly find specific types, use 
the Syntax Visualizer window from Visual Studio. This will interpret the current opened document as a Roslyn 
syntax tree. 

0 Comment's

Comment Form

Submit Comment