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); }