Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can a public class not inherit from a less visible one? [duplicate]

Possible Duplicate:
C#: Why can't my public class extend an internal class?

I apologize if this question has been asked before. I've searched SO somewhat and wasn't able to find it.

I'm just curious what the rationale behind this design was/is. Obviously I understand that private/internal members of a base type cannot, nor should they, be exposed through a derived public type. But it seems to my naive thinking that the "hidden" parts could easily remain hidden while some base functionality is still shared and a new interface is exposed publicly.

I'm thinking of something along these lines:

Assembly X

internal class InternalClass
{
    protected virtual void DoSomethingProtected()
    {
        // Let's say this method provides some useful functionality.
        // Its visibility is quite limited (only to derived types in
        // the same assembly), but at least it's there.
    }
}

public class PublicClass : InternalClass
{
    public void DoSomethingPublic()
    {
        // Now let's say this method is useful enough that this type
        // should be public. What's keeping us from leveraging the
        // base functionality laid out in InternalClass's implementation,
        // without exposing anything that shouldn't be exposed?
    }
}

Assembly Y

public class OtherPublicClass : PublicClass
{
    // It seems (again, to my naive mind) that this could work. This class
    // simply wouldn't be able to "see" any of the methods of InternalClass
    // from AssemblyX directly. But it could still access the public and
    // protected members of PublicClass that weren't inherited from
    // InternalClass. Does this make sense? What am I missing?
}
like image 423
Dan Tao Avatar asked Dec 31 '10 16:12

Dan Tao


2 Answers

What you're really asking for is a restricted form of non-public inheritance. In .NET, the base class is considered part of the interface, not an implementation detail. If you want to reuse another class in your implementation, you can of course use composition instead of inheritance.

Also note that implementing an interface with lesser visibility/accessibility IS allowed. The restriction you're asking about applies to base classes only.

like image 82
Ben Voigt Avatar answered Oct 08 '22 07:10

Ben Voigt


When a class inherits from a base class, the base members become part of the inherted class. In order to maintain this concept, the visibility scope of the base class must be equal or better than the inhertied class.

like image 32
k rey Avatar answered Oct 08 '22 08:10

k rey