8

I want to copy a List of Objects, but i keep getting references between the objects.

List<MyClass> copy = original;

When i change the value in the copy List, the original List ends up modified also. Is there a way to work around it?

ricojohari
  • 183
  • 1
  • 3
  • 12

1 Answers1

14

You can do this:

List<MyClass> copy = original.ToList();

This would make an element-by-element copy of the list, rather than copying the reference to the list itself.

Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
  • 1
    @ricojohari Could you please be more specific about the "not working" part? – Sergey Kalinichenko Mar 11 '13 at 03:36
  • 2
    when i changed the value of the copy list, the original list is getting modified too – ricojohari Mar 11 '13 at 03:43
  • @ricojohari Right - that's because the copy is *shallow*. If you add or remove items to/from the original, the copy is not going to "see" that change. However, changing mutable objects inside the list would be reflected in the copy as well. – Sergey Kalinichenko Mar 11 '13 at 03:45
  • would deep copy maintain the value in the original list even if the copy list is modified? – ricojohari Mar 11 '13 at 03:49
  • @ricojohari Yes. If you want a deep copy, use `List copy = original.Select(v => new MyClass(v)).ToList();` (assuming that `MyClass` has a "copy constructor" that takes an instance of the same class and returns a "deep copy" of the object). – Sergey Kalinichenko Mar 11 '13 at 03:51