diff --git a/src/NetAnalyzers/Core/Microsoft.NetCore.Analyzers/Runtime/AvoidConstArrays.cs b/src/NetAnalyzers/Core/Microsoft.NetCore.Analyzers/Runtime/AvoidConstArrays.cs index 9b1e46274b..48cc72f13e 100644 --- a/src/NetAnalyzers/Core/Microsoft.NetCore.Analyzers/Runtime/AvoidConstArrays.cs +++ b/src/NetAnalyzers/Core/Microsoft.NetCore.Analyzers/Runtime/AvoidConstArrays.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft. All Rights Reserved. Licensed under the MIT license. See License.txt in the project root for license information. +// Copyright (c) Microsoft. All Rights Reserved. Licensed under the MIT license. See License.txt in the project root for license information. using System.Linq; using System.Collections.Generic; @@ -103,7 +103,8 @@ public override void Initialize(AnalysisContext context) } // Must be literal array - if (arrayCreationOperation.Initializer.ElementValues.Any(x => x is not ILiteralOperation)) + if (arrayCreationOperation.Initializer is { } initializer && + initializer.ElementValues.Any(x => x is not ILiteralOperation)) { return; } diff --git a/src/NetAnalyzers/UnitTests/Microsoft.NetCore.Analyzers/Runtime/AvoidConstArraysTests.cs b/src/NetAnalyzers/UnitTests/Microsoft.NetCore.Analyzers/Runtime/AvoidConstArraysTests.cs index c30dd335a2..a529c8f17e 100644 --- a/src/NetAnalyzers/UnitTests/Microsoft.NetCore.Analyzers/Runtime/AvoidConstArraysTests.cs +++ b/src/NetAnalyzers/UnitTests/Microsoft.NetCore.Analyzers/Runtime/AvoidConstArraysTests.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft. All Rights Reserved. Licensed under the MIT license. See License.txt in the project root for license information. +// Copyright (c) Microsoft. All Rights Reserved. Licensed under the MIT license. See License.txt in the project root for license information. using System.Threading.Tasks; using Microsoft.CodeAnalysis.CSharp; @@ -804,5 +804,30 @@ private void M(string eventName, string msg) LanguageVersion = LanguageVersion.CSharp8 }.RunAsync(); } + + [Fact, WorkItem(6686, "https://github.com/dotnet/roslyn-analyzers/issues/6686")] + public Task ArrayWithoutInitializer_Diagnostic() + { + var source = @"using System.Collections.Generic; + +public class MyClass +{ + public List Cases => new() { {|CA1861:new object[0]|} }; +}"; + var fixedSource = @"using System.Collections.Generic; + +public class MyClass +{ + public List Cases => new() { item }; + + private static readonly object[] item = new object[0]; +}"; + return new VerifyCS.Test + { + TestCode = source, + FixedCode = fixedSource, + LanguageVersion = LanguageVersion.CSharp10 + }.RunAsync(); + } } }