Search code examples
c#overridingclass-design

Restricting subclasses from inheriting certain methods of base class


using System;

public class Base
{
    public Base()
    {
    }

    public void M1()
    {
    }

    public void M2()
    {
    }

    public void M3()
    {
    }
}

public class Derived : Base
{
    //this class should get only method 1
}

public class SecondDerived : Base
{
    //this class should get only method 2 and method3
}

The requirement is : the base class contains the 3 methods M1, M2, M3.
The derived class should inherit only M1 and SecondDerived should inherit only M2 and M3.

How can this be done?


Solution

  • It is not possible to do what you want with inheritance.

    It seems you have no intention of overriding, you simply want to "inherit" behavior from the base class selectively. You could do this using a "has a" relationship:

    public class Base
    {
         internal Base() {} //mark constructor as internal so it can not be used outside your assembly if necessary
    
         public Foo Mehtod1() {...}
         public Foo Mehtod2() {...}
         public Foo Mehtod3() {...}
    }
    

    Then simply do the following:

    class A
    {
         private Base internalBase;
    
         public A() { this.internalBase = new Base(); }
    
         public Foo Method1() { return this.internalBase.Method1(); }
    }
    
    class B
    {
         private Base internalBase;
    
         public A() { this.internalBase = new Base(); }
    
         public Foo Method2() { return this.internalBase.Method2(); }
         public Foo Method3() { return this.internalBase.Method3(); }
    }
    

    UPDATE: A possible alternative solution is to make your Base class methods virtual and override them all in your derived classes, throwing NotSupportedExceptions in those methods that you do not want the class to make available. I don't really like this solution but it has the advantage of not loosing the polyphormism inheritance gives you which might be useful if you have some core base functionality which all derived classes will share (in your example you seem to imply they wont).