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 re
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>
.
IList<T> list = new List<T>().AsReadOnly();
Or, if you want an IEnumerable<>
:
IEnumerable<T> sequence = Enumerable.Empty<T>();
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.
Construct an instance of System.Collections.ObjectModel.ReadOnlyCollection from your list.
List<int> items = new List<int>();
ReadOnlyCollection<int> readOnlyItems = new ReadOnlyCollection<int>(items);
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).
To expand on Dan Tao's answer, the following implementation can be used in the same way as Enumerable.Empty<T>()
, by specifying List.Empty<T>()
instead.
public static class List
{
public static IList<T> Empty<T>()
{
// Note that the static type is only instantiated when
// it is needed, and only then is the T[0] object created, once.
return EmptyArray<T>.Instance;
}
private sealed class EmptyArray<T>
{
public static readonly T[] Instance = new T[0];
}
}
Edit: I change the above code to reflect the outcome of a discussion with Dan Tao about lazy versus eager initialization of the Instance
field.