Yes - it helps. What I'm doing is writing a small console app for purposes
of me learning the strategy pattern. I'm adding reference member variables
to a base class. These reference variables are for adding "behavior" to
the base class (by holding an instance of a class that implements said
behavior). The derived classes then are supposed to implement whatever
behavior is relevant to the derived class BY instantiating and populating
the base class' "behavior variables".
This all works fine and well, but it dawned on me that there is nothing
*requiring* the derived class to implement the behavior (i.e., populate
the base class "behavior bariables".
Thus the question. As the designer of the original implementation here,
I'm thinking that [in a real-world scenario] future developers might add
new derived classes to the system without knowing that they must implement
the behavior (by populating the "behavior variables" in the base class).
By "must implement" I'm thinking that could be a requirement of the
real-world situation... where some class of objects MUST implement some
specific type(s) of behavior (thus they're in the base class) and the
particular behavior is known/added by the derived class at runtime. It
would apparently be up to the documentation (or runtime errors) to inform
the future/other developers that they must implement the behavior.
-Bob
Nicholas Paldino said:
Bob,
Internal protected allows internal classes to access the field as
well, so you might want to consider just protected if you want just base
classes to be able to access the field.
There really isn't way to enforce that the derived type populate the
field. The best way I can think of to do this is to set the default
value of the field to a value that is valid for the field type, but not
for what you are trying to do (e.g., 0 if it is an integer, null if it is
a reference type). Then, when your base class works with the field, and
it is the invalid value, you can throw an exception.
Hope this helps.
--
- Nicholas Paldino [.NET/C# MVP]
- (e-mail address removed)
Bob Johnson said:
I have a base class that must have a member variable populated by, and
only by, derived classes.
It appears that if I declare the variable as "internal protected" then
the base class *can* populate the variable, but the population is not
*required* by the derived class (which must be the case).
What would meet the requirements is if I create an abstract method in
the base class that populates the member variable. In this case the
derived classes would be required to implement the method.
Is there another way to meet the requirement?... specifically that a
member variable of a base class *must* be populated by a derived class
(and only by derived classes)?
Thanks!