Add parameter to method using Roslyn CodeFixProvider

I am writing Roslyn Code Analyzer , which I want to determine if the method asyncdoes not accept CancellationToken, and then suggest a code fix that adds it:

 //Before Code Fix:
 public async Task Example(){}

 //After Code Fix
 public async Task Example(CancellationToken token){}

I plugged DiagnosticAnalyzerin to properly report the diagnostics by checking methodDeclaration.ParameterList.Parameters, but I cannot find the Roslyn API to add Paramaterin ParameterListinside a CodeFixProvider.

This is what I have so far:

private async Task<Document> HaveMethodTakeACancellationTokenParameter(
        Document document, SyntaxNode syntaxNode, CancellationToken cancellationToken)
{
    var method = syntaxNode as MethodDeclarationSyntax;

    // what goes here?
    // what I want to do is: 
    // method.ParameterList.Parameters.Add(
          new ParameterSyntax(typeof(CancellationToken));

    //somehow return the Document from method         
}

How to update the method declaration and return the updated one Document?

+4
source share
1 answer

@Nate Barbettini , , MethodDeclarationSyntax, document SyntaxTree:

private async Task<Document> HaveMethodTakeACancellationTokenParameter(
        Document document, SyntaxNode syntaxNode, CancellationToken cancellationToken)
    {
        var method = syntaxNode as MethodDeclarationSyntax;

        var updatedMethod = method.AddParameterListParameters(
            SyntaxFactory.Parameter(
                SyntaxFactory.Identifier("cancellationToken"))
                .WithType(SyntaxFactory.ParseTypeName(typeof (CancellationToken).FullName)));

        var syntaxTree = await document.GetSyntaxTreeAsync(cancellationToken);

        var updatedSyntaxTree = 
            syntaxTree.GetRoot().ReplaceNode(method, updatedMethod);

        return document.WithSyntaxRoot(updatedSyntaxTree);
    }
+1

All Articles