I am trying to implement a code refactoring with .NET compiler platform (roslyn). However, for some reason I cannot make ObjectCreationExpression work with ArgumentList. Here is my method (whole code can be found here):
private aync Task<Document> AddGuardAsync(Document document, ParameterSyntax parameter, BaseMethodDeclarationSyntax methodDeclaration, CancellationToken cancellationToken)
{
BinaryExpressionSyntax binaryExpression = SyntaxFactory.BinaryExpression(SyntaxKind.EqualsExpression,
SyntaxFactory.IdentifierName(parameter.Identifier),
SyntaxFactory.LiteralExpression(SyntaxKind.NullLiteralExpression));
NameOfExpressionSyntax nameOfExp = SyntaxFactory.NameOfExpression(
"nameof",
SyntaxFactory.ParseTypeName(parameter.Identifier.Text));
SeparatedSyntaxList<ArgumentSyntax> argsList = new SeparatedSyntaxList<ArgumentSyntax>();
argsList.Add(SyntaxFactory.Argument(nameOfExp));
ObjectCreationExpressionSyntax objectCreationEx = SyntaxFactory.ObjectCreationExpression(
SyntaxFactory.ParseTypeName(nameof(ArgumentNullException)),
SyntaxFactory.ArgumentList(argsList),
null);
ThrowStatementSyntax throwStatement = SyntaxFactory.ThrowStatement(objectCreationEx);
IfStatementSyntax ifStatement = SyntaxFactory
.IfStatement(SyntaxFactory.Token(SyntaxKind.IfKeyword), SyntaxFactory.Token(SyntaxKind.OpenParenToken), binaryExpression, SyntaxFactory.Token(SyntaxKind.CloseParenToken), throwStatement, null)
.WithAdditionalAnnotations(Formatter.Annotation);
SyntaxNode root = await document.GetSyntaxRootAsync(cancellationToken);
SyntaxNode newRoot = root.InsertNodesBefore(methodDeclaration.Body.ChildNodes().First(), new[] { ifStatement });
return document.WithSyntaxRoot(newRoot);
}
This bizarrely produces the following code fix suggestion without the nameof argument (even without the curly braces):

What is it that I'm missing here?
SeparatedSyntaxList<T> is immutable.
Calling .Add() returns a new list with your token added.
You're ignoring that new list, so your token never appears anywhere.
You want
argsList = argsList.Add(SyntaxFactory.Argument(nameOfExp));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With