David R Tribble
David R Tribble

Reputation: 12214

C# private (hidden) base class

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.)

Upvotes: 18

Views: 13811

Answers (4)

Doug Royer
Doug Royer

Reputation: 65

I think this will work: Make the base class public, and make all of the methods protected. It helps keep them from being available and negates the need to re-implement or wrappers.

Upvotes: 0

Alexei Levenkov
Alexei Levenkov

Reputation: 100620

Depending on what "lot of common methods" are doing you may achieve some of it with internal extension methods:

internal static class MyStreamExtensions
{
   internal static int UsefulOne(this Stream stream)
   {
     return 42; 
   }
}   

Another approach is to make constructor internal to prevent unintentional derivation from that class:

public class BaseOutput: Stream
{
    internal BaseOutput(Stream o)
    { ... }

    ...lots of common methods...
}

This will make code more understandable compared to "not-really-visible" intermediate class in hierarchy.

Upvotes: 1

Jeff Watkins
Jeff Watkins

Reputation: 6357

Consider a pattern such as a Facade. That's what they're there for. I don't think you can achieve what you require with straight inheritance.

Upvotes: 5

CodesInChaos
CodesInChaos

Reputation: 108880

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.

Upvotes: 15

Related Questions