var source = @" public class MyClass { private int _myField = 0; public void MyMethod() { _myField++; } } "; var tree = CSharpSyntaxTree.ParseText(source); var root = tree.GetCompilationUnitRoot(); var tokens = root.ChildTokens(); foreach (var token in tokens) { Console.WriteLine(token.Kind()); }
var source = @" public class MyClass { private int _myField = 0; public void MyMethod() { _myField++; } } "; var tree = CSharpSyntaxTree.ParseText(source); var root = tree.GetCompilationUnitRoot(); var methodNode = root.DescendantNodes().OfTypeIn this example, we create a C# syntax tree from a string of source code, then get the root node of the syntax tree. We use the `DescendantNodes()` method to find the syntax node representing the `MyMethod()` method, then call the `ChildTokens()` method on that node to get all the tokens within the method. We then print out the text of each token. Both of these examples use the `Microsoft.CodeAnalysis.CSharp.Syntax` namespace, which is part of the `Microsoft.CodeAnalysis.CSharp` package.().Single(); var tokens = methodNode.ChildTokens(); foreach (var token in tokens) { Console.WriteLine(token.Text); }