Nick Nick - 7 days ago 6
C# Question

What is the use of a public constructor in a private class

I have the following class structure defined:

public sealed class PublicClass
{
private PrivateClass privateClass;

public PublicClass()
{
this.privateClass = new PrivateClass();
}

private sealed class PrivateClass
{
public PrivateClass()
{
}
}
}


Why is it necessary to make the constructor of PrivateClass "public" or "internal" in order to construct an instance of PrivateClass in the the PublicClass's constructor? Using "protected" or "private" modifiers on the PrivateClass constructor throw a compilation error.

Answer

In this case, you can't mark it as protected because you use sealed - that means nobody can`t inherit this class. To be able to create an instance of an object in this namespace you should use public or internal. You are not able to create this class in other namespaces.