Edit

Use collection expression for empty (IDE0301)

Property Value
Rule ID IDE0301
Title Use collection expression for empty
Category Style
Subcategory Language rules (expression-level preferences)
Applicable languages C# 12+
Options dotnet_style_prefer_collection_expression

Overview

This rule looks for code similar to Array.Empty() (a method call that returns an empty collection) or ImmutableArray.Empty (a property that returns an empty collection) and offers to replace it with a collection expression ([]).

Options

Options specify the behavior that you want the rule to enforce. For information about configuring options, see Option format.

dotnet_style_prefer_collection_expression

Property Value Description
Option name dotnet_style_prefer_collection_expression
Option values true | when_types_exactly_match Prefer to use collection expressions only when types match exactly, for example, List list = new List() { 1, 2 };.
when_types_loosely_match* Prefer to use collection expressions even when types match loosely, for example, IEnumerable list = new List() { 1, 2 };. The targeted type must match the type on the right-hand side or be one of the following types: IEnumerable, ICollection, IList, IReadOnlyCollection, IReadOnlyList.
false | never Disables the rule.
Default option value when_types_loosely_match*

*When this option is used, the code fix might change the semantics of your code.

Example

// Code with violations.
int[] i = Array.Empty();
IEnumerable j = Array.Empty();
ReadOnlySpan span = ReadOnlySpan.Empty;

// Fixed code.
int[] i = [];
IEnumerable j = [];
ReadOnlySpan span = [];

The following code snippet shows an example with a custom type.

public class Program
{
    public static void Main()
    {
        // IDE0301 violation.
        MyList x = MyList.Empty;

        // IDE0301 fixed code.
        MyList x = [];
    }
}

class MyList : IEnumerable
{
    public static MyList Empty { get; }

    public IEnumerator GetEnumerator() => default;
    IEnumerator IEnumerable.GetEnumerator() => default;
}

Suppress a warning

If you want to suppress only a single violation, add preprocessor directives to your source file to disable and then re-enable the rule.

#pragma warning disable IDE0301
// The code that's violating the rule is on this line.
#pragma warning restore IDE0301

To disable the rule for a file, folder, or project, set its severity to none in the configuration file.

[*.{cs,vb}]
dotnet_diagnostic.IDE0301.severity = none

To disable all of the code-style rules, set the severity for the category Style to none in the configuration file.

[*.{cs,vb}]
dotnet_analyzer_diagnostic.category-Style.severity = none

For more information, see How to suppress code analysis warnings.

See also