Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Handle null initializer for array creation operation #6696

Merged
merged 2 commits into from
Jun 19, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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()
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Verified AD0001 from this test prior to the fix

{
var source = @"using System.Collections.Generic;

public class MyClass
{
public List<object> Cases => new() { {|CA1861:new object[0]|} };
mavasani marked this conversation as resolved.
Show resolved Hide resolved
}";
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();
}
}
}