Rolan
Rolan

Reputation: 3004

How to convert an IMethodSymbol to a MethodDeclarationSyntax?

Given an IMethodSymbol how can I create a MethodDeclarationSyntax?

Background:

For a code fix, I'm copying methods from one class which implements an interface into another which implements a different one.

As a result, I need to modify a few things on the copied method (parameters, namespaces, etc.). I would like to modify the IMethodSymbol, convert the symbol into a MethodDeclarationSyntax and then add the symbol to the new class.

I have been able to do this by using the DeclaringSyntaxReferences property, but this doesn't work when the original class resides in a nuget package.

Using DeclaringSyntaxReferences (and some of my own code) I was able to do the following:

public static MethodDeclarationSyntax[] ToMethodDeclarationSyntax(this IMethodSymbol methodSymbol)
        {
            var namespaceValue = methodSymbol.ContainingNamespace.GetNameSpaceIdentifier();
            var syntaxReference = methodSymbol.DeclaringSyntaxReferences;
            var syntaxNodes = syntaxReference.Select(syntaxRef => syntaxRef.GetSyntax());
            var methodNodes = syntaxNodes.OfType<MethodDeclarationSyntax>();
            var methodExpression = methodSymbol.CreateExpressionSyntax();
            return methodNodes
                .Select(mds => mds
                    .WithExpressionBody(methodExpression)
                    .WithReturnType(SyntaxFactory.QualifiedName(namespaceValue, SyntaxFactory.IdentifierName(mds.ReturnType.ToString())))
                    .WithParameterList(methodSymbol.GetFullyQualifiedParameterListSyntax())
                )
                .ToArray();
        }

Is there a way to generate a MethodDeclarationSyntax from an IMethodSymbol without using DeclaringSyntaxReferences?

Thanks!

Upvotes: 3

Views: 618

Answers (1)

Jason Malinowski
Jason Malinowski

Reputation: 18976

Use SyntaxGenerator.MethodDeclaration which takes an IMethodSymbol. You probably don't want to be using DeclaringSyntaxReferences at all since that's only really useful in cases where your symbol came directly from source.

Upvotes: 5

Related Questions