1

Possible Duplicate:
Deep copy of List<T>

public class MyClass : ICloneable
{
    private List<string> m_list = new List<string>();
    public MyClass()
    {
        List.Add("1111");
        List.Add("2222");
        List.Add("3333");
        List.Add("4444");
    }

    public List<string> List
    {
        get { return m_list; }
        set { m_list = value; }
    }

    public object Clone()
    {
        return this.MemberwiseClone();
    }
}

example:

MyClass m  = new MyClass();
MyClass t = (MyClass)m.Clone();
m.List.Add("qweqeqw");
//m.List.Count == 5
t.ToString();
//t.List.Count==5

but I need a full copy of how to do this?

Community
  • 1
  • 1
Mediator
  • 14,951
  • 35
  • 113
  • 191
  • Have you looked at this: http://stackoverflow.com/questions/4226747/deep-copy-of-listt – RQDQ Jul 19 '11 at 01:15
  • it is actually recommended that IClonable is not to be used, as it makes no differentiation between the deep and the shallow copies. – Muad'Dib Jul 19 '11 at 02:00

1 Answers1

1

You need to distinguish between deep copy and shallow copy.

The appropriate way to deep copy is:

public MyClass DeepCopy()
{
    MyClass copy = new MyClass();

    copy.List = new List<string>(m_List);//deep copy each member, new list object is created

    return copy;
}

Where the ICloneable usually used for a shallow copy like:

public object Clone()
{
    MyClass copy = new MyClass();

    copy.List = List;//notice the difference here. This uses the same reference to the List object, so if this.List.Add it will add also to the copy list.

    return copy;

    //Note: Also return this.MemberwiseClone(); will do the same effect.
}
FishBasketGordo
  • 22,904
  • 4
  • 58
  • 91
Jalal Said
  • 15,906
  • 7
  • 45
  • 68
  • If MyClass is inheritable, the DeepCopy method indicated won't work. The proper approach for cloning is to have a protected virtual method which calls the base type's cloning method (or MemberwiseClone if the base type is Object); if cloning is to be exposed as a public interface, a non-virtual public clone method should call the private virtual one. – supercat Jul 19 '11 at 22:22
  • @supercat: Yes, you are right, I only wanted to demonstrate to him what is the different between deep and the shallow copy and how to initialize them... – Jalal Said Jul 20 '11 at 01:49