Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why Roslyn is generating method code without spaces

Tags:

c#

roslyn

What am I doing wrong that Roslyn is generating code without any space between identifiers and keywords? It is also putting a semicolon at the end of the method block. Here is my code:

SeparatedSyntaxList<ParameterSyntax> parametersList = new SeparatedSyntaxList<ParameterSyntax>().AddRange
(new ParameterSyntax[]
    {
        SyntaxFactory.Parameter(SyntaxFactory.Identifier("sender")).WithType(SyntaxFactory.ParseTypeName("object")),
        SyntaxFactory.Parameter(SyntaxFactory.Identifier("args")).WithType(SyntaxFactory.ParseTypeName("EventArgs"))
    }
);

MethodDeclarationSyntax newMethod = SyntaxFactory.MethodDeclaration(
    SyntaxFactory.List<AttributeListSyntax>(),
    SyntaxFactory.TokenList(SyntaxFactory.Token(SyntaxKind.PrivateKeyword)),
    SyntaxFactory.ParseName("void"),
    null,
    SyntaxFactory.Identifier("simpleButton1_Click"),
    null,
    SyntaxFactory.ParameterList(parametersList),
    SyntaxFactory.List<TypeParameterConstraintClauseSyntax>(),
    SyntaxFactory.Block(),
    SyntaxFactory.Token(SyntaxKind.SemicolonToken)
);

And here is the result that I am having:

privatevoidsimpleButton1_Click(objectsender,EventArgse){};
like image 715
WSK Avatar asked Oct 29 '15 14:10

WSK


1 Answers

To be even more comprehensive, NormalizeWhiteSpace should be mentioned. It applies default formatting to the given node:

MethodDeclarationSyntax newMethod = SyntaxFactory.MethodDeclaration(
    SyntaxFactory.List<AttributeListSyntax>(),
    SyntaxFactory.TokenList(SyntaxFactory.Token(SyntaxKind.PrivateKeyword)),
    SyntaxFactory.PredefinedType(SyntaxFactory.Token(SyntaxKind.VoidKeyword)),
    null,
    SyntaxFactory.Identifier("simpleButton1_Click"),
    null,
    SyntaxFactory.ParameterList(parametersList),
    SyntaxFactory.List<TypeParameterConstraintClauseSyntax>(),
    SyntaxFactory.Block(),
    null
  )

newMethod = newMethod.NormalizeWhitespace();

A ToString() on that will produce the expected output:

private void simpleButton1_Click(object sender, EventArgs args)
{
}
like image 61
Patrice Gahide Avatar answered Oct 24 '22 16:10

Patrice Gahide