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?
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?
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 MyObject
s or keep the originals. If you want to clone MyObject
you will need a way to clone them which typically is done through ICloneable
.
Or, you could do something like this:
public static class CloneClass
{
/// <summary>
/// Clones a object via shallow copy
/// </summary>
/// <typeparam name="T">Object Type to Clone</typeparam>
/// <param name="obj">Object to Clone</param>
/// <returns>New Object reference</returns>
public static T CloneObject<T>(this T obj) where T : class
{
if (obj == null) return null;
System.Reflection.MethodInfo inst = obj.GetType().GetMethod("MemberwiseClone",
System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic);
if (inst != null)
return (T)inst.Invoke(obj, null);
else
return null;
}
}
Then use it like:
var new1 = CloneClass.CloneObject<List<<MyObject>>(a1);
I think the general practice is to avoid using Clone because it's not clear if it's a Shallow vs Deep copy of the object.
More on that here: http://blogs.msdn.com/b/brada/archive/2004/05/03/125427.aspx
A fairly common solution has been to use the BinaryFormatter class to serialize/derialize an object and return the new instance, but with the caveat that the class must be serializable:
https://mcmap.net/q/9314/-how-do-you-do-a-deep-copy-of-an-object-in-net-duplicate
Assuming the above, you could do:
var clonedList = originaList.DeepClone();
© 2022 - 2024 — McMap. All rights reserved.