views:

122

answers:

5

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.

+7  A: 

You can just create a list:

List<MyType> list = new List<MyType>();

If you want an empty IEnumerable<T>, use Enumerable.Empty<T>():

IEnumerable<MyType> collection = Enumerable.Empty<MyType>();

If you truly want a readonly list, you could do:

IList<MyType> readonlyList = (new List<MyType>()).AsReadOnly();

This returns a ReadOnlyCollection<T>, which implements IList<T>.

Reed Copsey
I thought this too but then saw the readonly requirement. Then I thought what would be the point of an empty readonly List<T>. What am I missing?
Jay Riggs
There isn't really a readonly `List<T>`...
Reed Copsey
@Jay: I added that option, too...
Reed Copsey
+5  A: 
IList<T> list = new List<T>().AsReadOnly();

Or, if you want an IEnumerable<>:

IEnumerable<T> sequence = Enumerable.Empty<T>();
LukeH
+1  A: 

What about:

readonly List<T> mylist = new List<T>();

Not sure why you want it readonly; that doesn't make much sense in most scenarios I can think of, though.

CesarGon
Also, this doesn’t make the list read-only.
Timwi
Re: why, see edited question above.
David Moles
+3  A: 

If you want a list whose contents can't be modified, you can do:

ReadOnlyCollection<Foo> foos = new List<Foo>().AsReadOnly();
Bryan Watts
+2  A: 

Construct an instance of System.Collections.ObjectModel.ReadOnlyCollection from your list.

List<int> items = new List<int>();
ReadOnlyCollection<int> readOnlyItems = new ReadOnlyCollection<int>(items);
Richard Cook