blinkettaro
blinkettaro

Reputation: 361

Modifying body of method with Roslyn

Is there some way to add a specific statement at the end of a method in a .cs file with Roslyn?

var code = new StreamReader(@"C:\Users\PersonalUser\Documents\Visual Studio 2015\Projects\SampleToAnalyze\SampleToAnalyze\ClassChild.cs").ReadToEnd();
SyntaxTree tree = CSharpSyntaxTree.ParseText(code);
var root = tree.GetRoot();
var compilation = CSharpCompilation.Create("MyCompilation", new[] { tree },
          new[] { MetadataReference.CreateFromFile(typeof(object).Assembly.Location) });
var model = compilation.GetSemanticModel(tree);

MethodDeclarationSyntax myMethod= tree.GetRoot().DescendantNodes()
                                      .OfType<MethodDeclarationSyntax>().Last();

StatementSyntax myStatement= SyntaxFactory.ParseStatement(@"Console.WriteLine();");

I want to insert "myStatement" at the end of method "myMethod".

Upvotes: 7

Views: 2535

Answers (1)

svick
svick

Reputation: 244757

You can use the AddBodyStatements method to create a new MethodDeclarationSyntax with the statement added and then use ReplaceNode to update the SyntaxTree:

var newRoot = root.ReplaceNode(myMethod, myMethod.AddBodyStatements(myStatement));

This will create code that's valid C#, but looks wrong, because it's badly indented. Probably the simplest way to fix that is to also call Formatter.Format:

newRoot = Formatter.Format(newRoot, new AdhocWorkspace());

Upvotes: 10

Related Questions