Question

I've implemented singleton according to this page using System.Lazy<T>.

I wonder, how technically can System.Lazy<T> access constructor of T, when access modificator of constructor is private.

Was it helpful?

Solution

The Lazy<T> is instantiated with an anonymous method as follows:

new Lazy<Singleton>(() => new Singleton());

Anonymous methods are under the covers just private methods located in the class that defines them. Since this is a method in the class, it is allowed to access any other private members of that class including the private constructor.

The code the C# compiler generates closely resembles the following:

Func<Singleton> factory = this.__compiler_generated_method;
new Lazy<Singleton>(factory);

private static Singleton __compiler_generated_method()
{
    return new Singleton();
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top