From 23a9d9525feac5a83a17911c399638b13778a9a4 Mon Sep 17 00:00:00 2001 From: Omar Bonnet Date: Sun, 17 Nov 2024 20:33:57 -0500 Subject: [PATCH] Handle `using var` in redundant assignment removal - Adds a test to ensure redundant assignment removal respects the `using var` statement. - Relates to issue #72829. --- .../RemoveUnusedValueAssignmentTests.cs | 29 +++++++++++++++++++ ...scardDeclarationsWithAssignmentsService.cs | 3 ++ 2 files changed, 32 insertions(+) diff --git a/src/Analyzers/CSharp/Tests/RemoveUnusedParametersAndValues/RemoveUnusedValueAssignmentTests.cs b/src/Analyzers/CSharp/Tests/RemoveUnusedParametersAndValues/RemoveUnusedValueAssignmentTests.cs index c80e2492244f8..7000b894c5edb 100644 --- a/src/Analyzers/CSharp/Tests/RemoveUnusedParametersAndValues/RemoveUnusedValueAssignmentTests.cs +++ b/src/Analyzers/CSharp/Tests/RemoveUnusedParametersAndValues/RemoveUnusedValueAssignmentTests.cs @@ -10072,4 +10072,33 @@ public void Reset() { ReferenceAssemblies = ReferenceAssemblies.Net.Net80, }.RunAsync(); } + + [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/72829")] + public async Task RemoveRedundantAssignment_PreservesUsingVar() + { + await TestInRegularAndScriptAsync( + """ + class C + { + void M() + { + {|FixAllInDocument:int items = 0;|} + items = 42; + System.Console.WriteLine(items); + using var _ = System.IO.File.OpenRead("test.txt"); + } + } + """, + """ + class C + { + void M() + { + int items = 42; + System.Console.WriteLine(items); + using var _ = System.IO.File.OpenRead("test.txt"); + } + } + """); + } } diff --git a/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/CSharp/LanguageServices/CSharpReplaceDiscardDeclarationsWithAssignmentsService.cs b/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/CSharp/LanguageServices/CSharpReplaceDiscardDeclarationsWithAssignmentsService.cs index 6de1859a1714d..7ee8e87c1faed 100644 --- a/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/CSharp/LanguageServices/CSharpReplaceDiscardDeclarationsWithAssignmentsService.cs +++ b/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/CSharp/LanguageServices/CSharpReplaceDiscardDeclarationsWithAssignmentsService.cs @@ -49,6 +49,9 @@ public async Task ReplaceAsync( case LocalDeclarationStatementSyntax localDeclarationStatement: if (localDeclarationStatement.Declaration.Variables.Any(IsDiscardDeclaration)) { + // Skip replacing discard declarations in "using var" + if (localDeclarationStatement.UsingKeyword != default) continue; + RemoveDiscardHelper.ProcessDeclarationStatement(localDeclarationStatement, editor); }