1

Possible Duplicate:
How do I clone a generic list in C#?

I want to copy a list to another in C#. The problem is that existing methods like copyto creates a new list from another list. But if I make some changes to new list the old list also gets changed. Its because of their reference type behaviour. If there any way (apart from foreach loop) to create a new list from another list which will not reference the same object

Community
  • 1
  • 1
Sunny
  • 53
  • 1
  • 1
  • 3
  • 1
    This is called 'deep-cloning'. – leppie Dec 07 '12 at 06:31
  • Yes, the issue is deep copy vs. shallow copy. It is actually a big can of worms in programming languages. There are standard clone methods, but they are variously implemented in terms of shallow vs. deep, and relatively inconsistently from subclass to subclass. I suspect you're best off using the for loop unless you have some confidence that the collection implementations are yours. – Erik Eidt Dec 07 '12 at 06:34

1 Answers1

17

So what you want is a deep copy of the list -- where the 2nd list contains copies of the elements of the 1st list. In that case, when an element of any list changes, the other list remains unchanged.

How to do that, depends on whether the elements of your list are reference types or value types. A value type list can be easily cloned like so:

List<int> deepCopy = new List<int>(originalList);

For a reference type list, you can use serialization, like so:

public List<MyObject> DeepCopy()
{
    MemoryStream ms = new MemoryStream();
    BinaryFormatter bf = new BinaryFormatter();
    bf.Serialize(ms, this);

    ms.Position = 0;
    return (List<MyObject>) bf.Deserialize(ms);
}
Roy Dictus
  • 32,551
  • 8
  • 60
  • 76