Why doesn't the .net generic type List<T>
offer any Clone()
function?
Why doesn't it implement IClonable
?
The problem with cloning objects and, especially the ICloneable
interface, is that the public interface doesn't communicate the intention well.
Namely - will such Clone
function of the List<T>
clone contained elements as well, or just clone the list and copy the references to contained elements? Shallow copy, which copies the references and only creates the new list would be equivalent to this:
List<T> clone = new List<T>(originalList);
However, if you wanted to force all the contained elements to be cloned as well, then it would be equivalent to this:
List<T> clone = originalList.Select(x => (T)x.Clone()).ToList();
This assumes that the type T
is implementing ICloneable
. However, even with this solution, exact effects of code execution cannot be told in advance. What does it mean for an element x
to clone itself? Will it be a shallow copy (offered by the MemberwiseClone
method it inherits form System.Object
), or will it be a deep copy. And if deep, what will happen if two objects in the list are referencing the same third object? Will that third object be copied twice or only once? And so on... you can see where this is going.
For all the reasons listed above, cloning facilities are not incorporated in the framework. It is left to custom code to decide what it means to clone an object and then implement custom code for that.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With