Search code examples
c#inheritanceabstract

How to not inherit all variables and methods of an abstract class but only some, in C#?


I have a C# abstract class:

public abstract class BaseScript : MonoBehaviour
{
    public float numberOne = 5f;
    public float numberTwo = 10f;
    public float result;

    public void NumbersAdd()
    {
        result = numberOne + numberTwo;
    }

    public void NumbersMultiply()
    {
        result = numberOne * numberTwo;
    }
}

What I would like to do is have another class that inherits from this, but only partially, so that it only inherits the public float result variable and the NumbersAdd() method.

But currently when I create that class with public class InheritingScript : BaseScript, it causes it to inherit all methods and variables.

Is there a way to avoid this? I especially want to avoid grabbing all variables, as in my actual project this is hundreds of variables, and it is very clutter-y.

I tried simply creating an instance of the other class to communicate with it, but I am pretty sure I need it in a base/inheritance structure for my project's purpose.


Solution

  • Pretty simple stuff. If you inherit a class, you inherit all its members. If you want a derived class to only inherit some members of a base class then there must be some other base class from which only those members are inherited. Your own derived class would inherit the base class with only the members you want to inherit, e.g.

    public abstract class ClassA
    {
        public int FieldA;
    }
    
    public abstract class ClassB : ClassA
    {
        public int FieldB
    }
    
    public class ClassC : ClassA
    {
        // ...
    }
    

    If only ClassB were declared and had both member fields, ClassC inheriting ClassB would mean inheriting both fields. By splitting out the members into two classes with one inheriting the other, you can get all members by inheriting ClassB or just some members by inheriting ClassA. You can do this through as many layers of inheritance as you like.

    Consider how controls work in WinForms. The Panel class inherits ScrollableControl, which inherits Control, which inherits Component. Other classes may inherit ScrollableControl while others might inherit Control and others might inherit Comnponent, depending on what functionality they need to inherit. This is what makes an inheritance hierarchy a hierarchy.