Question

I have written an Analyzer that correctly detects uninstantiated collections. Now I'm writing the appropriate CodeFixProvider that will give the option to instantiate it.

When I execute my code and look at the provided fix, it would simply remove the identifier and only keep the type. Where did I go 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))
    };
}
Was it helpful?

Solution

You have to remember that all types in Roslyn are immutable. That means that even operations like Add() don't actually modify the object they're called on, they return the modified object.

This means that after Add(), you have to work with the returned value, not the original object.

If you modify your code to the following, it will work:

declarator = declarator.Add(SyntaxFactory.VariableDeclarator(identifier, null, equalsClause));
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top