C# private (hidden) base class

David R Tribble picture David R Tribble · Jun 2, 2012 · Viewed 11.6k times · Source

Is it possible to make a C# base class accessible only within the library assembly it's compiled into, while making other subclasses that inherit from it public?

For example:

using System.IO;

class BaseOutput: Stream           // Hidden base class
{
    protected BaseOutput(Stream o)
    { ... }

    ...lots of common methods...
}

public class MyOutput: BaseOutput  // Public subclass
{
    public BaseOutput(Stream o):
        base(o)
    { ... }

    public override int Write(int b)
    { ... }
}

Here I'd like the BaseOutput class to be inaccessible to clients of my library, but allow the subclass MyOutput to be completely public. I know that C# does not allow base classes to have more restrictive access than subclasses, but is there some other legal way of achieving the same effect?

UPDATE

My solution for this particular library is to make the base class public and abstract, and to document it with "Do not use this base class directly". I also make the constructor of the base class internal, which effectively prevents outside clients from using or inheriting the class.

(It's a shame, because other O-O languages let me have hidden base classes.)

Answer

CodesInChaos picture CodesInChaos · Jun 2, 2012

Unfortunately not. You can't derive a public class from an internal or private class.

You need to either expose the base class, or you need to declare all the methods for all of your similar classes. If you go the route where you declare all methods again, it's probably useful to create a helper class, which has the actual implementation of them. Still it's quite a bit of boilerplate.