Low-Design787

u/Low-Design787


r/csharp•

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 implementation

112