From 23ee3588d340ea036de544d768112fcffc8e7ee8 Mon Sep 17 00:00:00 2001 From: Collin Alpert Date: Thu, 7 Mar 2024 18:47:35 +0100 Subject: [PATCH] Generate field for const arrays in constructor declarations --- .../Runtime/AvoidConstArrays.Fixer.cs | 1 + .../Runtime/AvoidConstArraysTests.cs | 33 +++++++++++++++++++ 2 files changed, 34 insertions(+) diff --git a/src/NetAnalyzers/Core/Microsoft.NetCore.Analyzers/Runtime/AvoidConstArrays.Fixer.cs b/src/NetAnalyzers/Core/Microsoft.NetCore.Analyzers/Runtime/AvoidConstArrays.Fixer.cs index 99e9a69fa5..d675d297e2 100644 --- a/src/NetAnalyzers/Core/Microsoft.NetCore.Analyzers/Runtime/AvoidConstArrays.Fixer.cs +++ b/src/NetAnalyzers/Core/Microsoft.NetCore.Analyzers/Runtime/AvoidConstArrays.Fixer.cs @@ -74,6 +74,7 @@ private static async Task ExtractConstArrayAsync(Document document, Sy // Get method containing the symbol that is being diagnosed IOperation? methodContext = arrayArgument.GetAncestor(OperationKind.MethodBody); methodContext ??= arrayArgument.GetAncestor(OperationKind.Block); // VB methods have a different structure than CS methods + methodContext ??= arrayArgument.GetAncestor(OperationKind.ConstructorBody); // Create the new member SyntaxNode newMember = generator.FieldDeclaration( diff --git a/src/NetAnalyzers/UnitTests/Microsoft.NetCore.Analyzers/Runtime/AvoidConstArraysTests.cs b/src/NetAnalyzers/UnitTests/Microsoft.NetCore.Analyzers/Runtime/AvoidConstArraysTests.cs index 26c95331a0..c189f175db 100644 --- a/src/NetAnalyzers/UnitTests/Microsoft.NetCore.Analyzers/Runtime/AvoidConstArraysTests.cs +++ b/src/NetAnalyzers/UnitTests/Microsoft.NetCore.Analyzers/Runtime/AvoidConstArraysTests.cs @@ -1053,5 +1053,38 @@ partial class Program } }.RunAsync(); } + + [Fact, WorkItem(7216, "https://github.com/dotnet/roslyn-analyzers/issues/7216")] + public Task BaseDeclaration_Diagnostic() + { + const string code = """ + public class Class1 + { + public Class1(int[] arr) { } + } + + public class Class2 : Class1 + { + public Class2() + : base([|new int[] { 1, 2, 3 }|]) { } + } + """; + const string fixedCode = """ + public class Class1 + { + public Class1(int[] arr) { } + } + + public class Class2 : Class1 + { + private static readonly int[] arr = new int[] { 1, 2, 3 }; + + public Class2() + : base(arr) { } + } + """; + + return VerifyCS.VerifyCodeFixAsync(code, fixedCode); + } } }