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.
Personally, I think this is better than any of the other answers:
static readonly IList<T> EmptyList = new T[0];
IList<T>
.new List<T>().AsReadOnly()
. 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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With