ImmortalStrawberry
ImmortalStrawberry

Reputation: 6091

Best practice for getting a derived class to implement a property?

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?

Upvotes: 0

Views: 1186

Answers (3)

Andrew Kennan
Andrew Kennan

Reputation: 14157

Another option is to force derived classes to pass a value of Foo to the base class:

public abstract class A {
  private readonly BarType _foo;

  protected A(BarType foo) {
    _foo = foo;
  }

  // Does Foo need to be public or is it only used internally by A?
  public BarType Foo { get { return _foo; } }
}

public class B : A {

  public B() : base(BarType.Value1) {
  }
}

Upvotes: 5

Brian Kintz
Brian Kintz

Reputation: 1993

Assuming you're only returning a single value of the enum for each child class, the best way I know of is to implement an abstract property in the base class, then implement it in each child class.

public abstract class A {
    public BarType Foo;

    public enum BarType {
        Value1,
        Value2
    }
}

public class B : A {
    public BarType Foo { get { return BarType.Value1; } }
}

Upvotes: 1

Kevin Versfeld
Kevin Versfeld

Reputation: 720

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:

public BarType BarType{get{return BarType.WhaleFoo ;}}

Upvotes: 2

Related Questions