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?

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;
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))
};
}
source
share