Skip to content

Commit 9211f22

Browse files
Remove unnecessary parentheses from spread elements (#76348)
2 parents d610c11 + 4f7b405 commit 9211f22

File tree

2 files changed

+29
-0
lines changed

2 files changed

+29
-0
lines changed

src/Analyzers/CSharp/Tests/RemoveUnnecessaryParentheses/RemoveUnnecessaryExpressionParenthesesTests.cs

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3530,4 +3530,26 @@ public void M(object o, object?[] c)
35303530
}
35313531
""");
35323532
}
3533+
3534+
[Fact]
3535+
public async Task TestCollectionExpressionSpread()
3536+
{
3537+
await TestInRegularAndScript1Async("""
3538+
class C
3539+
{
3540+
public void M()
3541+
{
3542+
var v = [.. $$(a ? b : c)];
3543+
}
3544+
}
3545+
""", """
3546+
class C
3547+
{
3548+
public void M()
3549+
{
3550+
var v = [.. a ? b : c];
3551+
}
3552+
}
3553+
""");
3554+
}
35333555
}

src/Workspaces/SharedUtilitiesAndExtensions/Compiler/CSharp/Extensions/ParenthesizedExpressionSyntaxExtensions.cs

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -280,6 +280,13 @@ nodeParent is BinaryExpressionSyntax(SyntaxKind.CoalesceExpression) binary &&
280280
if (nodeParent is SwitchExpressionArmSyntax arm && arm.Expression == node)
281281
return true;
282282

283+
// [.. (expr)] -> [.. expr]
284+
//
285+
// Note: There is no precedence with `..` it's always just part of the collection expr, with the expr being
286+
// parsed independently of it. That's why no parens are ever needed here.
287+
if (nodeParent is SpreadElementSyntax)
288+
return true;
289+
283290
// If we have: (X)(++x) or (X)(--x), we don't want to remove the parens. doing so can
284291
// make the ++/-- now associate with the previous part of the cast expression.
285292
if (parentExpression.IsKind(SyntaxKind.CastExpression) &&

0 commit comments

Comments
 (0)