Skip to content

Commit 9aea0f4

Browse files
authored
Merge pull request #69812 from mavasani/Issue66975
Bail out from remove unused member analyzer for ??= operator
2 parents e6747ee + 290be62 commit 9aea0f4

File tree

2 files changed

+6
-4
lines changed

2 files changed

+6
-4
lines changed

src/Analyzers/CSharp/Tests/RemoveUnusedMembers/RemoveUnusedMembersTests.cs

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -7,9 +7,7 @@
77
using System.Threading.Tasks;
88
using Microsoft.CodeAnalysis.CSharp;
99
using Microsoft.CodeAnalysis.CSharp.RemoveUnusedMembers;
10-
using Microsoft.CodeAnalysis.Diagnostics;
1110
using Microsoft.CodeAnalysis.Editor.UnitTests.CodeActions;
12-
using Microsoft.CodeAnalysis.RemoveUnusedMembers;
1311
using Microsoft.CodeAnalysis.Shared.Extensions;
1412
using Microsoft.CodeAnalysis.Test.Utilities;
1513
using Microsoft.CodeAnalysis.Testing;
@@ -3097,12 +3095,13 @@ public class MyClass
30973095
}
30983096

30993097
[Fact, WorkItem("https://github.com/dotnet/roslyn/issues/32842")]
3098+
[WorkItem("https://github.com/dotnet/roslyn/issues/66975")]
31003099
public async Task FieldIsNotRead_NullCoalesceAssignment()
31013100
{
31023101
var code = """
31033102
public class MyClass
31043103
{
3105-
private MyClass {|IDE0052:_field|};
3104+
private MyClass _field;
31063105
public void M() => _field ??= new MyClass();
31073106
}
31083107
""";

src/Analyzers/Core/Analyzers/RemoveUnusedMembers/AbstractRemoveUnusedMembersDiagnosticAnalyzer.cs

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -342,8 +342,11 @@ memberReference.Parent is IIncrementOrDecrementOperation ||
342342
// Note that the increment operation '_f1++' is child of an expression statement, which drops the result of the increment.
343343
// while the increment operation '_f2++' is child of a return statement, which uses the result of the increment.
344344
// For the above test, '_f1' can be safely removed without affecting the semantics of the program, while '_f2' cannot be removed.
345+
// Additionally, we special case ICoalesceAssignmentOperation (??=) and treat it as a read-write,
346+
// see https://github.com/dotnet/roslyn/issues/66975 for more details
345347

346-
if (memberReference?.Parent?.Parent is IExpressionStatementOperation)
348+
if (memberReference?.Parent?.Parent is IExpressionStatementOperation &&
349+
memberReference.Parent is not ICoalesceAssignmentOperation)
347350
{
348351
valueUsageInfo = ValueUsageInfo.Write;
349352

0 commit comments

Comments
 (0)