diff --git a/RefactoringEssentials/CSharp/Diagnostics/Synced/RedundanciesInCode/RedundantCommaInArrayInitializerCodeFixProvider.cs b/RefactoringEssentials/CSharp/Diagnostics/Synced/RedundanciesInCode/RedundantCommaInArrayInitializerCodeFixProvider.cs index b5c35994..aa05f32b 100644 --- a/RefactoringEssentials/CSharp/Diagnostics/Synced/RedundanciesInCode/RedundantCommaInArrayInitializerCodeFixProvider.cs +++ b/RefactoringEssentials/CSharp/Diagnostics/Synced/RedundanciesInCode/RedundantCommaInArrayInitializerCodeFixProvider.cs @@ -46,11 +46,15 @@ public async override Task RegisterCodeFixesAsync(CodeFixContext context) return; var redundantComma = node.Expressions.GetSeparator(elementCount - 1); + var newSeparatedExpList = new List(node.Expressions.GetWithSeparators().Where(t => t != redundantComma)); + var lastExp = newSeparatedExpList.Last(); + newSeparatedExpList.RemoveAt(newSeparatedExpList.Count - 1); + newSeparatedExpList.Add(lastExp.WithTrailingTrivia(redundantComma.TrailingTrivia)); + var newRoot = root.ReplaceNode( node, node - .WithExpressions(SyntaxFactory.SeparatedList(node.Expressions.ToArray())) - .WithAdditionalAnnotations(Formatter.Annotation)); + .WithExpressions(SyntaxFactory.SeparatedList(SyntaxFactory.NodeOrTokenList(newSeparatedExpList)))); context.RegisterCodeFix(CodeActionFactory.Create(node.Span, diagnostic.Severity, "Remove ','", document.WithSyntaxRoot(newRoot)), diagnostic); } diff --git a/Tests/CSharp/Diagnostics/RedundantCommaInArrayInitializerTests.cs b/Tests/CSharp/Diagnostics/RedundantCommaInArrayInitializerTests.cs index 0e4049f9..76e4d417 100644 --- a/Tests/CSharp/Diagnostics/RedundantCommaInArrayInitializerTests.cs +++ b/Tests/CSharp/Diagnostics/RedundantCommaInArrayInitializerTests.cs @@ -95,5 +95,31 @@ void TestMethod () }"; Analyze(input); } + + [Test] + public void TestPreserveTrivia() + { + Analyze(@" +class TestClass +{ + void TestMethod() + { + var a = new int[] { + 1, + 2$,$ + }; + } +}", @" +class TestClass +{ + void TestMethod() + { + var a = new int[] { + 1, + 2 + }; + } +}"); + } } }