Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ObjectCreationExpression with ArgumentList inside CodeRefactoringProvider

Tags:

c#

.net

roslyn

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):

enter image description here

What is it that I'm missing here?

like image 705
tugberk Avatar asked Jun 30 '26 13:06

tugberk


1 Answers

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));
like image 110
SLaks Avatar answered Jul 03 '26 01:07

SLaks



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!