Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 897
Friend Avatar asked Mar 08 '12 17:03

Friend


People also ask

How do you clone a list?

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.

What is cloning of list in python?

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.


2 Answers

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.

like image 189
aqwert Avatar answered Sep 25 '22 23:09

aqwert


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);
like image 39
MAckerman Avatar answered Sep 26 '22 23:09

MAckerman