Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I clone a generic list in C#?

I have a generic list of objects in C#, and wish to clone the list. The items within the list are cloneable, but there doesn't seem to be an option to do list.Clone().

Is there an easy way around this?

like image 885
Fiona Avatar asked Oct 21 '08 16:10

Fiona


People also ask

What is clone () method in C?

C# | Clone() Method In C#, Clone() is a String method. It is used to clone the string object, which returns another copy of that data. In other words, it returns a reference to this instance of String. The return value will be only another view of the same data. Clone method called directly on current String instance.

Can lists be generic?

You can't declare a list of generic types without knowing the generic type at compile time. You can declare a List<Field<int>> or a List<Field<double>> , but there is no other common base type for Field<int> and Field<double> than object .


1 Answers

If your elements are value types, then you can just do:

List<YourType> newList = new List<YourType>(oldList); 

However, if they are reference types and you want a deep copy (assuming your elements properly implement ICloneable), you could do something like this:

List<ICloneable> oldList = new List<ICloneable>(); List<ICloneable> newList = new List<ICloneable>(oldList.Count);  oldList.ForEach((item) =>     {         newList.Add((ICloneable)item.Clone());     }); 

Obviously, replace ICloneable in the above generics and cast with whatever your element type is that implements ICloneable.

If your element type doesn't support ICloneable but does have a copy-constructor, you could do this instead:

List<YourType> oldList = new List<YourType>(); List<YourType> newList = new List<YourType>(oldList.Count);  oldList.ForEach((item)=>     {         newList.Add(new YourType(item));     }); 

Personally, I would avoid ICloneable because of the need to guarantee a deep copy of all members. Instead, I'd suggest the copy-constructor or a factory method like YourType.CopyFrom(YourType itemToCopy) that returns a new instance of YourType.

Any of these options could be wrapped by a method (extension or otherwise).

like image 164
Jeff Yates Avatar answered Sep 23 '22 03:09

Jeff Yates