Closure access to private constructor in C#

I understand how in C# closures allow access to private variables declared in the same scope as an anonymous method, so that those variables are available when the method is invoked in a different scope.

But what about private constructors? This code works:

class Program
{
    static void Main(string[] args)
    {
        var someClassFactory = SomeClass.GetFactoryMethod();

        var someclass = someClassFactory();
    }
}

class SomeClass
{
    private SomeClass()
    {
    }

    public static Func<SomeClass> GetFactoryMethod()
    {
        return () => new SomeClass();
    }
}

As the compiler creates a class for the closure, how does it then reference the private constructor, or otherwise allow it to be accessed when the anonymous method is invoked by the client code?

Jon Skeet
people
quotationmark

In this case, the compiler doesn't need to create a class at all - it can just create a static method:

public static Func<SomeClass> GetFactoryMethod()
{
    return __GeneratedMethod;
}

private static SomeClass __GeneratedMethod()
{
    return new SomeClass();
}

Even when it does need to generate a class - e.g. if GetFactoryMethod() had a parameter which was captured by the lambda expression - it would generate a nested class, and nested classes have access to the private members of their enclosing classes:

public class Foo
{
    private Foo() {}

    public class Bar
    {
        public Foo MakeNewFoo()
        {
            return new Foo(); // This is absolutely fine
        }
    }
}

people

See more on this question at Stackoverflow