All rules
IDE0301Language rules (expression-level preferences)

Use collection expression for empty

Use collection expression for empty

Microsoft docs

Description

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 ([]).

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 = [];

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;
}
Group results
0 yes 0 no
ConsensusNone (disabled)
Severity preference (yes voters)
Suggestion0
Warning0
Error0