Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Roslyn - how to reliably format whitespace for a class

Tags:

c#

roslyn

I need to format a class to ensure it's easily human readable. I have the syntax tree, the root CompilationUnitSyntax and the ClassDeclarationSyntax. I format the whitespace as follows.

root = root.ReplaceNode(classSyntax, classSyntax.NormalizeWhitespace(elasticTrivia: true));
syntaxTree = syntaxTree.WithRootAndOptions(root, syntaxTree.Options);

Before:

#region MyRegion
public class MyClass
{

    // Info about MyClass

}
#endregion

After:

#region MyRegion
public class MyClass
{
// Info about MyClass    
}#endregion

Why is the class's closing brace slammed into the #endregion?

If I run NormalizeWhitespace once more on the 'After' text, #endregion is moved back down onto its own line. Then a further call to NormalizeWhitespace moves it back up again. What is going on?

like image 235
DGreen Avatar asked Nov 09 '22 05:11

DGreen


1 Answers

This sounds like a bug, possibly related to https://github.com/dotnet/roslyn/issues/1066.

like image 64
Kevin Pilch Avatar answered Nov 14 '22 22:11

Kevin Pilch