Reputation: 1114
I'm struggling with replacing single statement with multiple statements inside the Roslyn code fix provider. When I invoke root.ReplaceNode(assignmentStatement, newStatements) I always get System.InvalidOperationException 'The item specified is not the element of a list.' I've found that probably the new list of nodes should starts with old one but I want to replace the whole current statement with multiple new statements. How can I accomplish that?
private async Task<Document> GenerateCodeFix(Document document, SyntaxToken culprit, CancellationToken cancellationToken)
{
var statement = FindAddigmentStatementToReplace(culprit.Parent);
if (statement == null)
{
return document;
}
var root = await document.GetSyntaxRootAsync(cancellationToken);
var newStatements = GenerateNewStatements()
var newRoot = root.ReplaceNode(assignmentStatement, newStatements)
return document.WithSyntaxRoot(newRoot);
}
Upvotes: 1
Views: 729
Reputation: 3513
You can use the ReplaceNode overload and pass the statements as an IEnumerable<SyntaxNode>
. For example:
var statement = ( StatementSyntax ) root.FindNode( diagnostic.Location.SourceSpan );
var statements = new SyntaxNode[]
{
SomeStatement() ,
SomeStatement()
};
return Task.FromResult( context.Document.WithSyntaxRoot( root.ReplaceNode( statement , statements ) ) );
Upvotes: 1