I often find myself in need to create empty collections. One of those days several years ago, I wrote something like the following to address that:
public static class Array<T>
{
// As a static field, it gets created only once for every type.
public static readonly T[] Empty = new T[0];
}
I didn't know about Enumerable<T>.Empty(); maybe it didn't exist back then. Although I know now, I still use this one. Maybe because I know the actual implemention or maybe I just overly used to it.
// All these variables share the same array's reference.
string[] empty1 = Array<string>.Empty;
IEnumerable empty2 = Array<string>.Empty;
IEnumerable<string> empty3 = Array<string>.Empty;
Although switching to Enumerable<T>.Empty() is probably the best since it's now the de facto way to create an empty collection but I still have my doubts.
I wrote this firstly because it does caching of its empty array references but MSDN says Enumerable<T>.Empty() does cache the empty results, too.
So the only advantage of using Array<T> I can think of now, is that it returns an array:
There are still many functions that need an array of values instead of IEnumerable<T>, IList<T> or IReadOnlyList<T>. And array implements all of these so it can be used anywhere.
What do you think about this class?
Can you see any other advantages/disadvantages of it over Enumerable<T>.Empty()?
And about implementation:
Do you think making the caching using a static field would cause any problem?
IEnumerable<Foo> GetRelatedFoos(Foo foo) { if (foo.Operations == 0) return Array<Foo>.Empty; return GetRelatedFoosInternal(foo); }whereGetRelatedFoosInternal(Foo foo)is an iterator block. By separating these methods I can avoid initializing the iterator's state machine unless necessary and by returningArray<Foo>.Emptyinstead ofnew Foo[0]I can use the single, emptyFoo[]instance for everyGetRelatedFooscall that should return empty. – Şafak Gür Jan 15 at 10:25