Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is `List<T>` not clonable? [closed]

Tags:

c#

list

Why doesn't the .net generic type List<T> offer any Clone() function?

Why doesn't it implement IClonable?

like image 765
user366312 Avatar asked Jan 05 '23 23:01

user366312


1 Answers

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.

like image 72
Zoran Horvat Avatar answered Jan 11 '23 19:01

Zoran Horvat