Is there a particular reason why a generic ICloneable<T>
does not exist?
It would be much more comfortable, if I would not need to cast it everytime I clone something.
Is there a particular reason why a generic ICloneable<T>
does not exist?
It would be much more comfortable, if I would not need to cast it everytime I clone something.
It's a very good question... You could make your own, though:
Andrey says it's considered a bad API, but i have not heard anything about this interface becoming deprecated. And that would break tons of interfaces... The Clone method should perform a shallow copy. If the object also provides deep copy, an overloaded Clone ( bool deep ) can be used.
EDIT: Pattern i use for "cloning" an object, is passing a prototype in the constructor.
This removes any potential redundant code implementation situations. BTW, talking about the limitations of ICloneable, isn't it really up to the object itself to decide whether a shallow clone or deep clone, or even a partly shallow/partly deep clone, should be performed? Should we really care, as long as the object works as intended? In some occasions, a good Clone implementation might very well include both shallow and deep cloning.
Although the question is very old (5 years from writing this answers :) and was already answered, but I found this article answers the question quite well, check it here
EDIT:
Here is the quote from the article that answers the question (make sure to read the full article, it includes other interesting things):
In addition to Andrey's reply (which I agree with, +1) - when
ICloneable
is done, you can also choose explicit implementation to make the publicClone()
return a typed object:Of course there is a second issue with a generic
ICloneable<T>
- inheritance.If I have:
And I implemented
ICloneable<T>
, then do I implementICloneable<Foo>
?ICloneable<Bar>
? You quickly start implementing a lot of identical interfaces... Compare to a cast... and is it really so bad?