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

3

15

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?

Anthropomorphic answered 8/3, 2012 at 17:41 Comment(1)
See: #223098Sherrer
E
35

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.

Euphemism answered 8/3, 2012 at 17:43 Comment(3)
How is his solution not treating all items?Bluey
var new1 = new List<MyObject>(a1); only works for value types, you should update your answer.Foreboding
var new1 = new List<MyObject>(a1.Select(x => x.Clone() as MyObject));Elishaelision
F
4

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);
Fluctuation answered 8/3, 2012 at 17:48 Comment(1)
You have one too many "<" 's. Should be <List<MyObject>>Shelia
L
1

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();
Limpopo answered 8/3, 2012 at 17:54 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.