-
Notifications
You must be signed in to change notification settings - Fork 4.2k
Open
Labels
Area-CompilersBugConcept-APIThis issue involves adding, removing, clarification, or modification of an API.This issue involves adding, removing, clarification, or modification of an API.Concept-Diagnostic ClarityThe issues deals with the ease of understanding of errors and warnings.The issues deals with the ease of understanding of errors and warnings.help wantedThe issue is "up for grabs" - add a comment if you are interested in working on itThe issue is "up for grabs" - add a comment if you are interested in working on it
Milestone

Description
I wrote a fixer like this, to mark a class as static:
private async Task<Document> MarkClassAsStatic(Document document, ClassDeclarationSyntax classDeclaration, CancellationToken c)
{
SyntaxToken classDeclarationToken = classDeclaration.Keyword;
SyntaxToken staticKeywordToken = SyntaxFactory.Token(SyntaxKind.StaticKeyword);
SyntaxNode root = await document.GetSyntaxRootAsync();
SyntaxNode newRoot = root.InsertTokensBefore(classDeclarationToken, new[] { staticKeywordToken });
Document newDocument = document.WithSyntaxRoot(newRoot);
return newDocument;
}
The call to InsertTokensBefore fails with the error "System.InvalidOperationException: The item specified is not the element of a list."
It turns out that the first argument to InsertTokensBefore must be an element of a list, and the "class" keyword is not an element of a list. In fact that's why the parameter name is tokenInList. Intellisense shows that, but when I saw the Intellisense for this method I had no idea what the name meant.
And it turns out there's a direct way to do what I want, using the AddModifiers method:
ClassDeclarationSyntax newClassDeclaration = classDeclaration.AddModifiers(new SyntaxToken[] { staticKeywordToken });
SyntaxNode root = await document.GetSyntaxRootAsync();
SyntaxNode newRoot = root.ReplaceNode(classDeclaration, newClassDeclaration);
Still, InsertTokensBefore was so seductive, it was really not obvious to me that it wouldn't work, and the error message didn't lead me towards the right answer.
Logerfo, allisonchou, Seteh and Rockdell
Metadata
Metadata
Assignees
Labels
Area-CompilersBugConcept-APIThis issue involves adding, removing, clarification, or modification of an API.This issue involves adding, removing, clarification, or modification of an API.Concept-Diagnostic ClarityThe issues deals with the ease of understanding of errors and warnings.The issues deals with the ease of understanding of errors and warnings.help wantedThe issue is "up for grabs" - add a comment if you are interested in working on itThe issue is "up for grabs" - add a comment if you are interested in working on it