22

So I have an abstract base class in a DLL and child classes of that class. I want the childs to be public, but the base to be private so that it cannot be accessed outside of the dll.

How do I do that?

Fionnuala
  • 90,370
  • 7
  • 114
  • 152
Ivan Prodanov
  • 34,634
  • 78
  • 176
  • 248

3 Answers3

36

You don't and you can't.

If you want to expose the class as public, the base-type must be public. One other option is to have a public interface, and only expose the type via the interface (presumably with a factory method somewhere for creating instances).

One final option is to encapsulate the base-class rather than inherit it.

Marc Gravell
  • 1,026,079
  • 266
  • 2,566
  • 2,900
  • Or all the methods/properties on the base class to be protected? but the class itself to be public? – Liam Nov 07 '12 at 13:09
  • @Liam that depends what you're trying to protect against; for example, if someone external can *subclass* it, they have access to those methods anyway. – Marc Gravell Nov 07 '12 at 13:10
  • 3
    @Liam yes, `internal` would prevent external people from getting easy access; of course, with reflection they can do most things anyway. – Marc Gravell Nov 07 '12 at 13:11
19

Make it public, make all constructors internal (if you're using the default constructor, add a parameterless constructor to override that).

Then while public and not sealed, it can't be sub-classed by external code.

Jon Hanna
  • 110,372
  • 10
  • 146
  • 251
2

Just to clarify what I was saying in comments on @Marc Gravel's answer you could

public ChildClass : ParentClass
{

}

public ParentClass
{
   internal void MethodIdontWantToExpose()
  {

  }

}

That said an interface is probably the best solution

Liam
  • 27,717
  • 28
  • 128
  • 190