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

后端 未结 8 2093
孤街浪徒
孤街浪徒 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:08

    To expand on Dan Tao's answer, the following implementation can be used in the same way as Enumerable.Empty(), by specifying List.Empty() instead.

    public static class List
    {
        public static IList Empty()
        {
            // Note that the static type is only instantiated when
            // it is needed, and only then is the T[0] object created, once.
            return EmptyArray.Instance;
        }
    
        private sealed class EmptyArray
        {
            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.

提交回复
热议问题