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?
To clone a list, one can iterate through the original list and use the clone method to copy all the list elements and use the add method to append them to the list. Approach: Create a cloneable class, which has the clone method overridden. Create a list of the class objects from an array using the asList method.
This method is considered when we want to modify a list and also keep a copy of the original. In this, we make a copy of the list itself, along with the reference. This process is also called cloning. This technique takes about 0.039 seconds and is the fastest technique.
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);
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