Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generating syntax for a method signature from a method symbol in Roslyn

Tags:

c#

.net

roslyn

I'm trying to generate code using Roslyn (first time user). I'm finding it so verbose that I can only assume I'm doing something wrong. At the moment I'm generating an implementation of a method for a given IMethodSymbol (which came from an interface):

private static MethodDeclarationSyntax GetMethodDeclarationSyntax(IMethodSymbol methodSymbol)
{
    if (methodSymbol.MethodKind != MethodKind.Ordinary)
    {
        return null;
    }

    var parameters = methodSymbol
        .Parameters
        .Select(x => SF
            .Parameter(SF.Identifier(x.Name))
            .WithType(SF.IdentifierName(x.Type.ToDisplayString(symbolDisplayFormat))));

    return SF
        .MethodDeclaration(
            SF.IdentifierName(methodSymbol.ReturnType.ToDisplayString(symbolDisplayFormat)),
            SF.Identifier(methodSymbol.Name))
        .WithModifiers(
            SF.TokenList(
                SF.Token(SyntaxKind.PublicKeyword)))
        .WithParameterList(
            SF.ParameterList(
                SF.SeparatedList<ParameterSyntax>(parameters)));
}

It's already pretty hefty and I haven't accounted for the actual implementation, generic parameters, ref/out parameters etcetera.

Is there a simpler way to achieve this?

like image 556
Kent Boogaart Avatar asked Dec 11 '25 01:12

Kent Boogaart


1 Answers

As of VS 2015 CTP 6 and the Roslyn 1.0-rc1 NuGet packages, take a look at the SyntaxGenerator class.

like image 149
Kevin Pilch Avatar answered Dec 12 '25 13:12

Kevin Pilch



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!