As svick answered you, you cannot modify an existing syntax tree. The Sytnax tree is immutable, but you can create another based on the existing one. To do this, you need to create a node and replace the existing one. Below you can use a simple example (change):
var name = Syntax.QualifiedName(Syntax.IdentifierName("System"), Syntax.IdentifierName("Collections")); name = Syntax.QualifiedName(name, Syntax.IdentifierName("Generic")); SyntaxTree tree = SyntaxTree.ParseText( @"using System; using System.Collections; using System.Linq; using System.Text; namespace HelloWorld { class Program { static void Main(string[] args) { Console.WriteLine(""Hello, World!""); } } }"); var root = (CompilationUnitSyntax)tree.GetRoot(); var oldUsing = root.Usings[1]; var newUsing = oldUsing.WithName(name); root = root.ReplaceNode(oldUsing, newUsing); Console.WriteLine(root.GetText());
In case of invariance, there is a note from the document Getting Started:
The underlying principle of the Roslyn API is immutability. Since immutable data structures cannot be changed after they are created, they can be safely shared and analyzed by several consumers at the same time without the risk that one tool will affect the other in an unpredictable way. No locks or other concurrency measures are required. This applies to syntax trees, compilation, symbols, semantic models, and every other data structure in the Roslyn API. Instead of modification, new objects are created based on the given differences with the old ones. You apply this concept to syntax trees to create tree transformations!
source share