dotnet / roslyn-analyzers

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

CA1812 generates false positive when class is created using collection initialization

RachelDavids opened this issue · comments

Analyzer

CA1812

Analyzer source

SDK: Built-in CA analyzers in .NET 5 SDK or later

Version: SDK 9.0.100-preview.1.24101.2

Describe the bug

Steps To Reproduce

    public class Class1
    {
        private readonly MyCollection _items = [];
        public int CurrentCount => _items.Count;
        public void AddItem(int value)
        {
            _items.Add(value);
        }
    }
    internal sealed class MyCollection
        : Collection<int>
    {

    }
    public class Class2
    {
#pragma warning disable IDE0028 // Simplify collection initialization
        private readonly MyCollection2 _items = new();
#pragma warning restore IDE0028 // Simplify collection initialization
    }
    internal sealed class MyCollection2
        : Collection<int>
    {

    }

Expected behavior

No warning/error

Actual behavior

  Error CA1812: 'MyCollection' is an internal class that is apparently never instantiated. If so, remove the code from the assembly. If this class is intended to contain only static members, make it 'static' (Module in Visual Basic). (https://learn.microsoft.com/dotnet/fundamentals/code-analysis/quality-rules/ca1812) (14, 27)

Additional context

Using SDK 8.0.200 produces the same behavior