Skip to content

Commit 30128dd

Browse files
Add language version check for compound assignment null propagation
Compound assignments with null conditional (?.) are only supported in C# 14+. Added language version check to ensure the diagnostic is only offered when supported. Added test to verify diagnostic is not offered for C# 13. Co-authored-by: CyrusNajmabadi <4564579+CyrusNajmabadi@users.noreply.github.com>
1 parent 692ad0d commit 30128dd

File tree

2 files changed

+20
-1
lines changed

2 files changed

+20
-1
lines changed

src/Analyzers/CSharp/Tests/UseNullPropagation/UseNullPropagationTests.cs

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3006,4 +3006,22 @@ static void M(C c)
30063006
}
30073007
}
30083008
""", languageVersion: LanguageVersion.CSharp14);
3009+
3010+
[Fact]
3011+
public Task TestIfStatement_CompoundAssignment_NotAvailableInCSharp13()
3012+
=> TestMissingInRegularAndScriptAsync(
3013+
"""
3014+
using System;
3015+
3016+
class C
3017+
{
3018+
event Action SomeEvent;
3019+
3020+
static void M(C c)
3021+
{
3022+
if (c is not null)
3023+
c.SomeEvent += () => { };
3024+
}
3025+
}
3026+
""", LanguageVersion.CSharp13);
30093027
}

src/Analyzers/Core/Analyzers/UseNullPropagation/AbstractUseNullPropagationDiagnosticAnalyzer.cs

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -448,8 +448,9 @@ private static TExpressionSyntax RemoveObjectCastIfAny(
448448

449449
// Check if node itself is a compound assignment. We do this by checking if the first child node
450450
// is on the left side of a compound assignment (which means the node is the compound assignment itself).
451+
// Compound assignments with null conditional (?.) are only supported in C# 14+.
451452
var firstChild = node.ChildNodesAndTokens().FirstOrDefault().AsNode();
452-
if (firstChild != null && syntaxFacts.IsLeftSideOfCompoundAssignment(firstChild))
453+
if (firstChild != null && syntaxFacts.IsLeftSideOfCompoundAssignment(firstChild) && syntaxFacts.SupportsNullConditionalAssignment(node.SyntaxTree.Options))
453454
{
454455
syntaxFacts.GetPartsOfAssignmentExpressionOrStatement(node, out var left, out _, out _);
455456
return (TExpressionSyntax)left;

0 commit comments

Comments
 (0)