Let's say I have the following class hierarchy (including the base interface):
IAction -> (abstract) BaseAction -> (concrete) ImmediateAction -> (concrete) MovementAction
Now let's say that IAction provides a method (well, really, a different interface that implements IAction, but let things simplify here!):
Ok so far? We have a deep copy method, and ImmediateAction has some properties that it wants to copy, so it will provide not only the DeepClone() implementation, but also a copy constructor:
//Base Action implementation protected BaseAction(BaseAction old) { this.something = old.something; } //Immediate Action Implementation protected ImmediateAction(ImmediateAction old) : base(old) { this.anything = old.anything; } public IAction DeepClone() { return new ImmediateAction(this); }
Now, let's say MovementAction has nothing inside of it that matters in DeepClone() at all, so it doesn't implement a copy method or constructor.
The problem I encountered is this:
IAction x = new MovementAction(); IAction y = x.DeepClone(); //pleaseBeTrue is false bool pleaseBeTrue = y is MovementAction;
Now I understand what is happening here - MovementAction does not implement DeepClone() , so ImmediateAction.DeepClone() is called instead, which creates a new ImmediateAction . Therefore, the type y in the above example is ImmediateAction instead of MovementAction .
So, after this long preamble, my question is: what is the best practice for this type of situation? I am stuck? I just had to implement the DeepClone() method no matter what for each class in the hierarchy? Is the pattern I use here wrong and is there a better way ?
One final note: I would like to avoid reflection, if at all possible.