Initializing empty IEnumerable property

In my code, this line gives warning IDE0301, “initialization can be simplified”:

public IEnumerable<Product> Products { get; set; } = Enumerable.Empty<Product>();

and suggests the following fix:

public IEnumerable<Product> Products { get; set; } = [];

Great, I thought, collection expressions are great. However Copilot (and the docs) say Enumerable.Empty is more efficient because it caches a singleton, whereas [] (becoming Array.Empty) creates a new empty array for every instance.

So is the warning misleading here? Usually I like having these warnings turned on.

Note collection expressions are smart and [] can resolve to different implementations according to context:

public List<T> MyList { get; } = [];
..becomes..
private readonly List<T> <MyList>k__BackingField = new List<T>();

public T[] MyArray { get; } = [];
..becomes..
private readonly T[] <MyArray>k__BackingField = Array.Empty<T>();

public ICollection<T> MyCollection { get; } = [];
..becomes..
private readonly ICollection<T> <MyCollection>k__BackingField = new List<T>();

Perhaps they need to enhance the implementation to expand to Enumerable.Empty when appropriate.

Posted Jun 3, 2024, 3:26 PM UTC

112

Comments aren't archived yet

This post had 12 comments on Reddit. Comments for this period haven't been loaded into the archive yet.