How to make correct clone of the List<MyObject>?

DmitryBoyko picture DmitryBoyko · Mar 8, 2012 · Viewed 69.7k times · Source

Possible Duplicate:
How do I clone a generic list in C#?

List<MyObject> a1 = new List<MyObject>();

var new1 = a1;

Now if I change a1 then new1 is going to be changed as well.

So my question is how to make a clone of a1 correctly?

Answer

aqwert picture aqwert · Mar 8, 2012

This wont Clone each item in the list but will create you a new list

var new1 = new List<MyObject>(a1);

If you want to clone each Item in the list you can implement ICloneable on MyObject

var new1 = new List<MyObject>(a1.Select(x => x.Clone()));

EDIT: To make it a bit clearer both will copy the elements from list a1 into a new list. You just need to decide if you want to have new MyObjects or keep the originals. If you want to clone MyObject you will need a way to clone them which typically is done through ICloneable.