Is there an "Empty List" singleton in C#?

Solution 1:

You are looking for Enumerable.Empty<T>().

In other news the Java empty list sucks because the List interface exposes methods for adding elements to the list which throw exceptions.

Solution 2:

Enumerable.Empty<T>() is exactly that.

Solution 3:

I think you're looking for Enumerable.Empty<T>().

Empty list singleton doesn't make that much sense, because lists are often mutable.

Solution 4:

In your original example you use an empty array to provide an empty enumerable. While using Enumerable.Empty<T>() is perfectly right, there might other cases: if you have to use an array (or the IList<T> interface), you can use the method

System.Array.Empty<T>()

which helps you to avoid unnecessary allocations.

Notes / References:

  • the documentation does not mention that this method allocates the empty array only once for each type
  • roslyn analyzers recommend this method with the warning CA1825: Avoid zero-length array allocations
  • Microsoft reference implementation
  • .NET Core implementation