Like any other C# programmer, I face the problem of how best to express the copying of objects.
Specifically, I have a class hierarchy in which all objects must be copyable.
It has already been discussed whether to use copy constructors (which C# doesn't provide) or a Clone()
method; another option is to use a method that takes an object and produces a copy.
All options have pros and cons, but one issue common to all of them is the typing problem.
I would like to state, in whatever way possible, that there exists a copy operation on all objects in my class hierarchy that always produces an object of the same type as the original - in such a way that any violation against this is reported at compile time.
None of these three options allow me to do this, even with generics. Apparently, C# doesn't allow me to do it at all; neither do Java and some other languages I know.
Why not? Is such a feature in the type system too hard to implement? Does it cause inconsistencies? Is my wish for an accurately typed copy operation considered a corner case? Is there some other way of achieving this that I've missed?
PS: Please note that this question is not about the difference between shallow and deep copy, how to copy, or whether to do it at all.
Part of the issue here is polymorphism. Creating a generic
ICloneable<T>
is trivial, but you get into problems when you have:because now
Bar
needs to implement bothICloneable<Foo>
andICloneable<Bar>
. Fortunately, you can use method hiding and polymorphism together to make this just about work, i.e.However! As you can see, this quickly gets painful to maintain. Perhaps a better option is to use the inbuilt non-generic
ICloneable
and an extension method:and then you can just have
Foo : ICloneable
, and just use:with your
Foo
/Bar
just: