Search code examples
.netencapsulationpublicclass-libraryinternal

Exposing an internal class as a public property


In a class library I am working on, I had a class with lots of properties so I refactored it to be composed of a few smaller, internal classes. However, now I have marked these classes as internal, the code won't compile when I expose them as public properties on the original class. For example:

public class TheOriginalClass
{
    public MyInternalClass InternalClassProperty { get; set; }
}

// It doesn't make sense to use this by itself
internal class MyInternalClass
{
    public string InterestingProperty { get; set; }
}

Ideally, I would like to encapsulate these helper classes within the assembly as it doesn't make sense for them to be instantiated anywhere else.

Is there a way to achieve this?


Solution

  • If you're exposing the content of the class to the outer world, mark it as public so you'll later know that the class is a publicly visible one so you'll be reluctant to change the public interface so often. There is not point in marking it internal if that's not going to be internal like that.

    If you really want that, use reflection with the calling assembly and with the binding flag BindingFlags.NonPublic while retrieving the classes (and their constructors) in the assembly.