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

Viewed 18024

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.

8 Answers

Starting with .net 4.6 you can also use:

IList<T> emptyList = Array.Empty<T>();

This does only create a new instance once for every different type you specify as T.

Related