Ties
Ties

Reputation: 1245

What is the canonical way to convert a MethodDeclarationSyntax to a ConstructorDeclarationSyntax?

I'm writing an analyzer and codefix for an API migration (AutoMapper V5 Profiles), converting a protected override Configure method to a constructor:

from:

public class MappingProfile : Profile
{
    protected override Configure()
    {
        CreateMap<Foo, Bar>();
        RecognizePrefix("m_");
    }
}

to

public class MappingProfile : Profile
{
    public MappingProfile()
    {
        CreateMap<Foo, Bar>();
        RecognizePrefix("m_");
    }
}

I've found a way to convert the method node into a constructor, but I've been struggling a lot to get the whitespace right. This begs the question if I'm not overlooking a simpler way of converting a method to constructor.

So my question is: does Roslyn already give you a refactoring to convert a MethodDeclarationSyntax to a ConstructorDeclarationSyntax? Or an easier way than this LINQPad script.

Upvotes: 1

Views: 456

Answers (1)

Kris Vandermotten
Kris Vandermotten

Reputation: 10201

In a CodeFix, just add the formatter annotation:

SyntaxFactory
    .ConstructorDeclaration(constructorIdentifier)
    .‌​WithModifiers(Syntax‌​Factory.TokenList(Sy‌​ntaxFactory.Token(Sy‌​ntaxKind.PublicKeywo‌​rd)))
    .WithAttributeL‌​ists(oldMethodNode.A‌​ttributeLists)
    .WithP‌​arameterList(newPara‌​meterList)
    .WithBody(‌​newBody)
    .WithTriviaF‌​rom(oldMethodNode)
    .W‌​ithAdditionalAnnotat‌​ions(Formatter.Annot‌​ation)

That's enough to do the trick in a code fix, because the code fix infrastructure will process the annotation.

Outside of a CodeFix, you can use Formatter.Format() from Microsoft.CodeAnalysis.Formatting to process the annotation explicitely.

Upvotes: 2

Related Questions