Search code examples
c#roslyn

Why Roslyn is generating method code without spaces


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){};

Solution

  • I think it's putting the semicolon there because you are passing one to the method that creates the method declaration, I'm guessing this is used when declaring an abstract method without a body.

    To correctly format the output you could use the Formatter class in the Microsoft.CodeAnalysis.Formatting namespace.

    Workspace workspace = MSBuildWorkspace.Create();
    SyntaxNode formattedNode = Microsoft.CodeAnalysis.Formatting.Formatter.Format(newMethod, workspace);
    

    For the return type you could do the following

    SyntaxFactory.PredefinedType(SyntaxFactory.Token(SyntaxKind.VoidKeyword));   
    

    This will give you a TypeSyntax