From 3d59049166d19c5288362cfec3fc7be7e9135bc9 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. - closes issue #72829. --- .../RemoveUnusedValueAssignmentTests.cs | 29 +++++++++++++++++++ ...scardDeclarationsWithAssignmentsService.cs | 6 ++++ 2 files changed, 35 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..5b4c5b3e3ebde 100644 --- a/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/CSharp/LanguageServices/CSharpReplaceDiscardDeclarationsWithAssignmentsService.cs +++ b/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/CSharp/LanguageServices/CSharpReplaceDiscardDeclarationsWithAssignmentsService.cs @@ -49,6 +49,12 @@ 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); }