Редактиране

Споделяне чрез


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<T>() (a method call that returns an empty collection) or ImmutableArray<T>.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, int[] i = Array.Empty<int>();.
when_types_loosely_match
(.NET 9 and later versions)*
Prefer to use collection expressions even when types match loosely, for example, IEnumerable<int> i = Array.Empty<int>();. The targeted type must match the type on the right-hand side or be one of the following types: IEnumerable<T>, ICollection<T>, IList<T>, IReadOnlyCollection<T>, IReadOnlyList<T>.
false | never Disables the rule.
Default option value true in .NET 8
when_types_loosely_match in .NET 9 and later versions

*The code fix when this option is used might change the semantics of your code.

Example

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

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

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

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

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

class MyList<T> : IEnumerable<T>
{
    public static MyList<T> Empty { get; }

    public IEnumerator<T> 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