Search code examples
c#collectionsgeneric-collections

C# / .NET equivalent for Java Collections.<T>emptyList()?


What's the standard way to get a typed, readonly empty list in C#, or is there one?

ETA: For those asking "why?": I have a virtual method that returns an IList (or rather, post-answers, an IEnumerable), and the default implementation is empty. Whatever the list returns should be readonly because writing to it would be a bug, and if somebody tries to, I want to halt and catch fire immediately, rather than wait for the bug to show up in some subtle way later.


Solution

  • Personally, I think this is better than any of the other answers:

    static readonly IList<T> EmptyList = new T[0];
    
    • Arrays implement IList<T>.
    • You cannot add to an array.
    • You cannot assign to an element in an empty array (because there is none).
    • This is, in my opinion, a lot simpler than new List<T>().AsReadOnly().
    • You still get to return an IList<T> (if you want).

    Incidentally, this is what Enumerable.Empty<T>() actually uses under the hood, if I recall correctly. So theoretically you could even do (IList<T>)Enumerable.Empty<T>() (though I see no good reason to do that).