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!