HiveBrain v1.2.0
Get Started
← Back to all entries
patterncsharpMinor

Cached empty collections

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
emptycachedcollections

Problem

I often need to return empty collections.

One of those days I wrote the following to return a cached instance:

public static class Array
{
    // 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.Empty() maybe it didn't exist back then. Although I know now, I still use this one.

There are still many functions in BCL that need an array instead of IEnumerable, IList or IReadOnlyList. And array implements all of these so it can be used anywhere.

// All these variables share the same array's reference.
string[]            empty1 = Array.Empty;
IEnumerable         empty2 = Array.Empty;
IEnumerable empty3 = Array.Empty;


What do you think about this class?

Can you see any other advantages/disadvantages of it over Enumerable.Empty()?

And about implementation:

Do you think making the caching using a static field would cause any problem?

Edit: Array class now has a static, generic Empty method, essentially deprecating this implementation.

Solution

Your solution is absolutely correct and practical.

In fact Enumerable.Empty also returns empty array under the hood, just slightly in a different way (they have a separate instance holder class that is lazily initialized).

Context

StackExchange Code Review Q#20417, answer score: 4

Revisions (0)

No revisions yet.