I would like to specialise a base class by adding new events and methods to it. For example, class B inherits from class A. However, if in code I hold a reference to my class B instance as its base type, A. Am I required to downcast everytime I need to access something from it from B, e.g. subscribe to EventB1, or call MethodB1?
if (obj is B)
{
B m = (B)obj;
m.EventB1 += EventHandlerB1;
}
Also, if I have a switch statement in my base class as above. Is it bad practice to add more cases to it in B?
Class A
{
public event EventHandler EventA1
public void MethodA1()
{
//some code
}
protected virtual void ProcessWorkItem(workItem type)
{
switch (type)
{
case workItem.A1:
..
break;
case workItem.A2:
..
break;
case workItem.A3:
..
break;
}
}
}
Class B : A
{
public event EventHandler EventB1
public void MethodB1()
{
//some code
}
protected override void ProcessWorkItem(workItem type)
{
base.ProcessWorkItem(type);
switch (type)
{
case workItem.B1:
..
break;
case workItem.B2:
..
break;
case workItem.B3:
..
break;
}
}
}
Absolutely. This should tell you there’s a design smell here. It doesn’t mean it’s necessarily bad, but it should at least prompt you to consider whether there’s a cleaner approach.
It’s hard to tell without knowing more about what it’s trying to do. It’s not clear whether using composition instead of inheritance would help you here, but it’s usually something worth thinking about. You may also want to consider using interfaces – both
AandBcould implement the same interface, withBcomposing anAif required. Maybe. It’s hard to tell 🙂