Follow these steps:
ISelf<T>
with a read-only Self
property that returns T
, and ICloneable<out T>
, which derives from ISelf<T>
and includes a method T Clone()
.CloneBase
type which implements a protected virtual generic VirtualClone
casting MemberwiseClone
to the passed-in type. VirtualClone
by calling the base clone method and then doing whatever needs to be done to properly clone those aspects of the derived type which the parent VirtualClone method hasn't yet handled.For maximum inheritance versatility, classes exposing public cloning functionality should be sealed
, but derive from a base class which is otherwise identical except for the lack of cloning. Rather than passing variables of the explicit clonable type, take a parameter of type ICloneable<theNonCloneableType>
. This will allow a routine that expects a cloneable derivative of Foo
to work with a cloneable derivative of DerivedFoo
, but also allow the creation of non-cloneable derivatives of Foo
.