Partial Exposure

Quite by accident, I just came across a useful syntax feature of using internal classes and interfaces: Partially exposing an internal class outside the containing assembly.

The basic pattern is this:

  • Create your partially exposed class as internal
  • Create an interface for the pieces of the class you want publicly visible and have the class implement the interface
  • Create a public factory that returns your internal class cast to the interface.

I thought this would cause a compilation or at least runtime error, since your factory returns an internal class. But it doesn't. It returns an object implementing the public interface. Since the underlying class is internal to its assembly, it can never be cast back to its originating type. The public members not exposed by the interface become virtually private. The nice thing is, that they are still public to classes that reside in the same assembly.

What is still funky is that you can take that object and call GetType and it will tell you the name of the internal type. You just can access that type.

Playing with this, i realized that the debugger can see all this quite nicely. It was then that i realized, that really, nothing is ever functionally internal or private. It's all just semantics. With Reflection, you can poke around any object as much as you want.