Skip to content

Commit

Permalink
Merge pull request #6696 from mavasani/Issue6686
Browse files Browse the repository at this point in the history
Handle null initializer for array creation operation
  • Loading branch information
mavasani committed Jun 19, 2023
2 parents 6e440ef + 1a70e89 commit ebd3126
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 3 deletions.
Original file line number Diff line number Diff line change
@@ -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;
Expand Down Expand Up @@ -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;
}
Expand Down
Original file line number Diff line number Diff line change
@@ -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;
Expand Down Expand Up @@ -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<object> Cases => new() { {|CA1861:new object[0]|} };
}";
var fixedSource = @"using System.Collections.Generic;
public class MyClass
{
public List<object> Cases => new() { item };
private static readonly object[] item = new object[0];
}";
return new VerifyCS.Test
{
TestCode = source,
FixedCode = fixedSource,
LanguageVersion = LanguageVersion.CSharp10
}.RunAsync();
}
}
}

0 comments on commit ebd3126

Please sign in to comment.