How to add an instance to an existing variable?

I wrote an analyzer that correctly detects unreasonable collections. Now I am writing the corresponding CodeFixProvider, which will make it possible to create it.

When I execute my code and look at the provided patch, it just removes the identifier and saves only the type. Where am I wrong in my approach?

enter image description here

public async Task<IEnumerable<CodeAction>> GetFixesAsync(Document document, TextSpan span, IEnumerable<Diagnostic> diagnostics, CancellationToken cancellationToken)
{
    var root = await document.GetSyntaxRootAsync(cancellationToken);
    var token = root.FindToken(span.Start);
    document.TryGetSemanticModel(out var semanticModel);
    var statement = token.Parent.Parent as VariableDeclarationSyntax;

    // Construct variable declaration
    var declarator = new SeparatedSyntaxList<VariableDeclaratorSyntax>();
    var identifier = statement.Variables[0].Identifier;
    var newType = semanticModel.GetTypeInfo(statement.Type).Type;
    var newObject = SyntaxFactory.ObjectCreationExpression(type: SyntaxFactory.ParseTypeName(newType.Name));
    var equalsClause = SyntaxFactory.EqualsValueClause(newObject);
    declarator.Add(SyntaxFactory.VariableDeclarator(identifier, null, equalsClause));

    var newStatement = SyntaxFactory.VariableDeclaration(statement.Type, declarator);
    var newRoot = root.ReplaceNode(statement, newStatement);

    return new[]
    {
        CodeAction.Create("Instantiate collection variable", document.WithSyntaxRoot(newRoot))
    };
}
+4
source share
1 answer

You must remember that all types in Roslin are unchanged. This means that even operations of the type Add()do not actually change the object to which they are called, they return the changed object.

, Add() , .

, :

declarator = declarator.Add(SyntaxFactory.VariableDeclarator(identifier, null, equalsClause));
+2

Source: https://habr.com/ru/post/1537754/


All Articles