Using private constructors in embedded classes

Hi. I have a pretty simple question, though I don't know if it has a simple answer:

I would like to define a class-within-a-class such that the embedded class can only be created by the outer class, but once created can be accessed publicly (similar to a factory pattern):

class A {
public class B {
private B() { ... }
}

public B CreateB() {
return new B();
}
}

This doesn't work as written, I get A.B.B() is inaccessible due to its protection level, and I get "inconsistent accessibility" errors with any other configuration I try. Is there some other protection level that will allow B.B() to be accessible to A, but not to anything outside of A

Also, I'm not super clear on this "inconsistent accessibility" concept. Visual studio generates classes with no qualifier, and this is apparently different than "public" classes. Could you explain what this means exactly

Thanks.


Answer this question

Using private constructors in embedded classes

  • Fred Robinson

    Axe22 wrote:

    If the class is public then it must have a constructor accessible from anywhere. If you don't, how can the class be public Nobody outside would be able to create one so therefore it isn't public. This is the paradox you're looking at.

    A public class doesn't need to have a public c'tor... A public class means the type can be used publicly, not that the c'tor is accessible.

  • R Raghu

    If the class is public then it must have a constructor accessible from anywhere. If you don't, how can the class be public Nobody outside would be able to create one so therefore it isn't public. This is the paradox you're looking at.


  • VBAddict

    Thanks, that's better than nothing!

  • Zoe Elmo

    The only thing you can do is to give the c'tor internal access so the c'tor can only be called from within the same assembly. An application that uses your assembly would not be able to call the c'tor and be forced to use the CreateB() method.

  • Using private constructors in embedded classes