Let’s say I have the following class hierarchy (base interface included):
IAction -> (abstract) BaseAction -> (concrete) ImmediateAction -> (concrete) MovementAction
Now, let’s say IAction exposes a method (well, really a different interface that IAction implements does but let’s keep things simple here!):
// Returns a new IAction instance deep copied from the current instance.
IAction DeepClone();
Good so far? We have our deep copy method, and ImmediateAction has some properties that it wants copied so it will provide not only an implementation of DeepClone(), but a copy constructor as well:
//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 doesn’t have anything inside of it that’s relevant in a DeepClone() at all, so it doesn’t implement the method or a copy constructor.
The problem that I’m having is this:
IAction x = new MovementAction();
IAction y = x.DeepClone();
//pleaseBeTrue is false
bool pleaseBeTrue = y is MovementAction;
Now, I understand what’s going on here – MovementAction does not implement DeepClone(), so ImmediateAction.DeepClone() is called instead, which instantiates a new ImmediateAction. Hence, the type of y in the above example is ImmediateAction instead of MovementAction.
So, after this lengthy preamble, my question is this: what is the best practice for this type of situation? Am I stuck? Do I simply have to implement a DeepClone() method no matter what for every class along the hierarchy? Is the pattern that I am using here incorrect, and there’s a better way?
One final note: I would like to avoid reflection if at all possible.
Could use an extension method and do incremental cloning