4

I'm writing a Roslyn Diagnostic with Code Fix. If there's a try block with one empty catch block, i want to provide the option to remove the catch block and replace the try block with its content. My problem is the outdenting of the content of the try block. I tried using the Formatter, but the lines are still indentend one level too much. Here's my code:

private async Task<Document> RemoveTryCatchBlockAsync(Document document, TryStatementSyntax tryBlock, CancellationToken cancellationToken)
{
    var oldRoot = await document.GetSyntaxRootAsync(cancellationToken);
    var newRoot = oldRoot.ReplaceNode(tryBlock, tryBlock.Block.ChildNodes());
    Formatter.Format(newRoot, MSBuildWorkspace.Create());

    // Return document with transformed tree. 
    return document.WithSyntaxRoot(newRoot);
}
martin
  • 225
  • 1
  • 10

1 Answers1

4

Roslyn is very immutable, your Formatter won't be changing the original node but instead return you a new one that is formatted.

Instead, try this:

var formattedRoot = Formatter.Format(newRoot, MSBuildWorkspace.Create());
return document.WithSyntaxRoot(formattedRoot);
Jeroen Vannevel
  • 43,651
  • 22
  • 107
  • 170