Reputation: 2428
This is another one of my "I think it's not possible but I need confirmation" questions.
I have a base class for a bunch of child classes. Right now, this base class has a few common properties the children use, like Name
. The base is an abstract class (MustInherit). Technically, this means that everytime a child class is instantiated, it lugs around, in memory, its own copy of Name
. The thing is, Name
is going to be a fixed value for all instances of a given child. I.e., Child1.Name
will return "child_object1"
, and Child2.Name
will return "child_object2"
.
This property seems a perfect candidate for a shared property, but then the problem arises. It seems that if I define Name
as a shared property in the base class, regardless of what children classes derive from base, all will share the same Name
, which is the exact purpose of shared properties (or methods, etc).
The only workaround that I can think of for this is to remove Name
from the base class and re-implement it as a shared property directly in each child class. This seems to defeat the function of having a base class in the first place, though. At least in principle.
So my question is what is the preferred approach to tackling this problem from a design standpoint? Assume at least 50 derived child classes from a single, abstract base class.
Upvotes: 0
Views: 1878
Reputation: 168988
I assume when you say "child object" you mean "child class." Don't mix up the terminology; it makes your question more confusing.
That said, I have used this pattern myself many times. You are right to think of shared/static, but you can't apply it here since each instance of a class derived from the base class can have a different name. I see nothing at all wrong with having an abstract property that is overridden to return a constant value.
Think about it -- the purpose of an abstract member is to allow child classes to provide their own implementation of it. When you ask an object "what is your name?" something needs to know. The child class itself is the perfect place for such data, and implementing an abstract member makes perfect sense.
If the Name property will be returning something based on the name of the type itself, you can obtain that with GetType().Name
, and therefore might be able to consolidate some of the name code into a default, virtual implementation of the property, and override it when the default implementation doesn't do the right thing. This could eliminate a lot of boilerplate code for a negligible performance penalty.
(To answer the question posed in your question title, yes, technically all non-private shared/static members of a type are inherited by all subtypes. But you cannot override them, because that makes no sense for shared/static members.)
Upvotes: 1