Given a simple class hierarchy where each class is derived from an abstract base class. Every derived class will need to somehow provide an enum “value” which the base class will use in certain base methods.
e.g.
Base class:
public abstract class AbstractFoo
{
bool SaveFoo()
{
switch (BarType){...}
}
}
and derived classes
public class BananaFoo:AbstractFoo
{
//barttype = fruit;
}
public class WhaleFoo:AbstractFoo
{
//barttype = mammal;
}
There are a number of ways I can make sure that ALL classes derived from AbstractFoo implement a property “enum BarType”
public abstract BarType BarType{get;}
In each derived class I can then implement BarType to return the correct type, or add an abstract method to do a very similar thing.
public BarType BarType{get{return _bartype;}}
OR add a concrete method to return a field – then I need to remember to add the field, but it’s a lot less typing (C&P)?
What is the recommended way to do this?
I can’t comment on what the correct way to do this is, but I’ve always used an abstract property on the base type (to force implementation), and then returned a constant from the subtype property.
for example: