Skip to content

IDE0306: Collection initialization can be simplified #77177

@bart-vmware

Description

@bart-vmware

This new warning appears during a command-line build and it appears after a full solution build in the VS Error List. After a double-click on the target file, it opens and the warning disappears from the Error List.

Also, the analyzer link https://learn.microsoft.com/dotnet/fundamentals/code-analysis/style-rules/ide0306 returns a 404.

Version Used:
.NET SDK 9.0.200, Visual Studio 2022 v17.12.5

Steps to Reproduce:

using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;

public class ActuatorMetadataProvider
{
    protected string DefaultContentType { get; }

    public ActuatorMetadataProvider(string defaultContentType)
    {
        ArgumentNullException.ThrowIfNull(defaultContentType);

        DefaultContentType = defaultContentType;
    }

    public virtual EndpointMetadataCollection GetMetadata(string httpMethod)
    {
        ArgumentException.ThrowIfNullOrEmpty(httpMethod);

        List<object> metadata = [];

        if (httpMethod is "DELETE" or "POST" or "PUT" or "PATCH")
        {
            metadata.Add(new ConsumesAttribute(DefaultContentType));
        }

        if (httpMethod != "OPTIONS")
        {
            metadata.Add(new ProducesAttribute(DefaultContentType));
        }

        return new EndpointMetadataCollection(metadata); // <-- warning reported here
    }
}

Full source at: https://github.com/SteeltoeOSS/Steeltoe

I don't understand why a warning is reported, or how to fix it. EndpointMetadataCollection implements IReadOnlyList<object>, IReadOnlyCollection<object> and IEnumerable<object> and has no Add method.

Diagnostic Id:

IDE0306: Collection initialization can be simplified

Expected Behavior:
No warning.

Actual Behavior:
Warning, which disappears after opening the file.

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions