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

后端 未结 8 2087
孤街浪徒
孤街浪徒 2020-12-29 02:11

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

8条回答
  •  甜味超标
    2020-12-29 03:03

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

    static readonly IList EmptyList = new T[0];
    
    • Arrays implement IList.
    • 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().AsReadOnly().
    • You still get to return an IList (if you want).

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

提交回复
热议问题