Search code examples
c#.netlinq.net-core

C# accessing static variable with generics (EmptyEnumerable<TElement>.Instance)


I was looking into the implementation of:

 Enumerable.Empty<...>()

And I noticed that under the hood it employs this:

    public static IEnumerable<TResult> Empty<TResult>() => (IEnumerable<TResult>) EmptyEnumerable<TResult>.Instance;

Which in turn employs this:

    internal class EmptyEnumerable<TElement>
    {
        public static readonly TElement[] Instance = new TElement[0];
    }

I can barely understand how this works. Can someone break it down for me? How does the compiler and the runtime handle this?

What I mean to say is that for every call to .Empty<>():

   Enumerable.Empty<string>()
   Enumerable.Empty<int>()
   Enumerable.Empty<SomeCustomClass>()

The runtime must construct reusable singleton / persistent class instances:

   EmptyEnumerable<string>
   EmptyEnumerable<int>
   EmptyEnumerable<SomeCustomClass>

and these instances (being singletons) never get disposed - they just get reused if we attempt a call with one of the types we have already used on .Empty<>().

Right? Or am I missing something?


Solution

  • Mostly this pattern is used for caching objects.

    Each time you requested an empty array via calling Empty property, it returns same object always. It doesn't create new objects each Empty call with same T parameter.

    EDIT: In that case, It's not creating any instance of your SomeCustomClass, just creates an array of SomeCustomClass. It doesn't matter if generic parameter type heavy to initilize or not.