using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; using System; class Program { static void Main(string[] args) { // C# code to be parsed string code = @" class MyClass { void Method1() { } void Method2() { } } "; // Parse code into a syntax tree SyntaxTree syntaxTree = CSharpSyntaxTree.ParseText(code); // Get the root of the syntax tree SyntaxNode root = syntaxTree.GetRoot(); // Find all method declarations and retrieve their names var methodDecls = root.DescendantNodes().OfType(); foreach (var methodDecl in methodDecls) { Console.WriteLine(methodDecl.Identifier.ValueText); } } }
using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Syntax; class Program { static void Main(string[] args) { // C# code to be parsed string code = @" class MyClass { void Method1() { int x = 10; int y = 20; int z = x + y; } } "; // Parse code into a syntax tree SyntaxTree syntaxTree = CSharpSyntaxTree.ParseText(code); // Get the root of the syntax tree SyntaxNode root = syntaxTree.GetRoot(); // Find all variable declarations and rename them var varDecls = root.DescendantNodes().OfTypeIn this example, we use C# Parser to parse a C# code snippet and rename the variables in it. We first use the CSharpSyntaxTree class to parse the code into an abstract syntax tree, and then use the DescendantNodes method to find all VariableDeclarationSyntax nodes in the tree. We then generate a new identifier for each variable and use the ReplaceNode method to replace the old identifier with the new one. Finally, we print the modified code using the ToFullString method.(); foreach (var varDecl in varDecls) { // Get the variable identifier var id = varDecl.Variables.First().Identifier; // Generate a new identifier var newId = SyntaxFactory.Identifier($"{id.ValueText}_new"); // Replace the old identifier with the new one var newVarDecl = varDecl.ReplaceNode(id, newId); // Replace the old variable declaration with the new one root = root.ReplaceNode(varDecl, newVarDecl); } // Print the modified code Console.WriteLine(root.ToFullString()); } }