Let's say there are classes D1, D2, etc. describing different types of an abstract class D.
Let's say there are SenderReceiver classes SenderReceiverD1, SenderReceiverD2, etc. describing different ways of communicating for each D1, D2, etc.:
abstract class SenderReceiver {
abstract void SendA();
public void Close() { /* Code */ }
}
abstract class SenderReceiverPlus : SenderReceiver {
abstract void SendB();
}
class SenderReceiverD1 : SenderReceiverPlus {
override void SendA() { /* Code */ }
override void SendB() { /* Code */ }
}
class SenderReceiverD2 : SenderReceiver {
override void SendA() { /* Code */ }
}
abstract class D {
SenderReceiver S;
abstract void DoThing();
}
class D1 : D {
D1 () { S = new SenderReceiverD1(); }
override void DoThing() {
S.SendA();
S.SendB();
S.Close();
}
}
class D2 : D {
D2 () { S = new SenderReceiverD2(); }
override void DoThing() {
S.SendA();
S.Close();
}
}
And there is a class with a list of D objects:
class Controller {
List<D> ds;
public Controller() {
ds = new List<D>();
ds.Add(new D1());
ds.Add(new D2());
}
public DoAllThings() {
foreach (D d in ds) {
d.DoThing();
}
}
}
This does not work because D1's reference to S references a SenderReceiver and so SendB() is not assuredly there.
I've considered empty virtual methods in the base class, casting S to the correct type in D1 and D2, and not having S in the D class. None of these are particularly satisfying.
Is there a better way to do this?