When I wrote about Array.Empty<T>(), one of the common questions readers asked was:
What is the difference between
Array.Empty<T>()andEnumerable.Empty<TResult>()?
The primary difference is the return type: Array.Empty<T>() returns T[] (an array), whereas Enumerable.Empty<TResult>() returns IEnumerable<TResult> (an enumerable).
You’re going to be able to do more with the result of Array.Empty<T>() than Enumerable.Empty<TResult>() as arrays implement the gamut of collection interfaces (e.g. IList<T>, IReadOnlyList<T>, ICollection<T>, IReadOnlyCollection<T>, IEnumerable<T>, etc.), in addition to all the functionality that Array itself provides.
There’s also a difference in layering:
-
Array.Empty<T>()is at the lowest layer on theSystem.Arraytype inSystem.Runtime.dllin .NET Core (mscorlib.dllin .NET Framework). -
Enumerable.Empty<TResult>()is in a higher layer on theSystem.Linq.Enumerabletype inSystem.Linq.dllin .NET Core (System.Core.dllin .NET Framework).
In .NET Framework, Array.Empty<T>() and Enumerable.Empty<TResult>() each have their own separate caches, but I recently changed Enumerable.Empty<TResult>() in .NET Core to simply return the result of calling Array.Empty<T>(), so both are now backed by the same cache in .NET Core. I’m not sure when/if this change will flow into a future version of .NET Framework.
Going forward, I’ll be using Array.Empty<T>() over Enumerable.Empty<TResult>() as Array.Empty<T>()’s return type provides more functionality (array vs. IEnumerable<T>) and requires less dependencies (lower layer).
Questions or comments? I'm @justinvp on Twitter.