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

user166390 picture user166390 · Dec 19, 2011 · Viewed 36k times · Source

In C# I use LINQ and IEnumerable a good bit. And all is well-and-good (or at least mostly so).

However, in many cases I find myself that I need an empty IEnumerable<X> as a default. That is, I would like

for (var x in xs) { ... }

to work without needing a null-check. Now this is what I currently do, depending upon the larger context:

var xs = f() ?? new X[0];              // when xs is assigned, sometimes
for (var x in xs ?? new X[0]) { ... }  // inline, sometimes

Now, while the above is perfectly fine for me -- that is, if there is any "extra overhead" with creating the array object I just don't care -- I was wondering:

Is there "empty immutable IEnumerable/IList" singleton in C#/.NET? (And, even if not, is there a "better" way to handle the case described above?)

Java has Collections.EMPTY_LIST immutable singleton -- "well-typed" via Collections.emptyList<T>() -- which serves this purpose, although I am not sure if a similar concept could even work in C# because generics are handled differently.

Thanks.

Answer

Stilgar picture Stilgar · Dec 19, 2011

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.