Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible a class to inherit only some(not all) base class members?

Is there a way that a derived class could inherit only a few of all the base class members..in C#? If such maneuver is possible, please provide some example code.

like image 375
CSharp4eto Avatar asked May 10 '16 17:05

CSharp4eto


Video Answer


2 Answers

Is there a way that a derived class could inherit only a few of all the base class members..in C#?

Yes. Make a base class that has one method, one constructor and one destructor. It has three new members, plus the heritable members of its base class. Now derive a class from that. The constructor and destructor will not be inherited; all the other members will. Therefore it is possible to create a derived class which inherits only some of its base class's members.

I suspect that answer is unsatisfying.

If your question is actually "is there a way that a base class can restrict what heritable members are inherited by a derived class?" the answer is no. Derived classes inherit all heritable members of base classes, regardless of their accessibility.

If your question is "is there a way that a derived class can choose which heritable members to inherit from a base class?" the answer is no. Derived classes inherit all heritable members of base classes, regardless of their accessibility.

Further reading, if this topic interests you:

https://ericlippert.com/2011/09/19/inheritance-and-representation/

like image 75
Eric Lippert Avatar answered Sep 19 '22 15:09

Eric Lippert


When you make a type inherit from another, you get everything - both the good and the "bad" bits from the parent type ("bad", in this context, meaning something you didn't want to have).

You can hide something from the parent class in the child class through the new modifier. However, take this advice from years of experience... More often than not this leads to a lot of work being spent on doing workarounds in the way the child class works. You'll spare yourself from a lot of trouble if instead of going this way, you redesign your classes.

If a child type has to clip off functionalities from a parent type, you probably have a design flaw in the parent. Reshape it to have less funcionality. You can have its different features redistributed among different children. A class doesn't always have to be an only child, you know ;)

like image 39
Geeky Guy Avatar answered Sep 18 '22 15:09

Geeky Guy