Convert data type from inherited classes in C#

Your problem stems from the fact that the base classes are poorly designed in the first place, in the following ways:

  • The hierarchy makes no sense. A behaviour is not a special kind of position. Prefer composition to inheritance.

  • Fields should never be public. Use properties, not fields.

  • “is” checks are runtime type checks; don’t do runtime type checks for polymorphic behaviour; use virtual methods.

Let’s redesign your hierarchy.

abstract class MyBehaviour
{
    public Position Position { get; private set; }
    public Handler Handler { get; private set; }
    protected MyBehaviour(int x, int y, Handler handler) {
        this.Position = new Position(x, y);
        this.Handler = handler;
    }
}
class Behaviour1 : MyBehaviour {
  /* Whatever */
}
class Behaviour2 : MyBehaviour {
  /* Whatever */
}

All right, and now when we want to execute the handler…

 MyBehaviour b = whatever;
 b.Handler.Enter();

Done. No temporary variable needed. No runtime type check. No “if”. The behaviour provides a service; you use the service. You should not have to ask the behaviour its type in order to use the service it provides; if you do, something is probably wrong at the design level.

Leave a Comment