1

I'm experiencing a problem in my C# code and I'm sure it has to do with the way I'm using reflection, but I'm not sure how to fix it.

To the best of my knowledge, if I have:

List1 = List<MyClass>

and use a syntax similar to

List2 = new List<MyClass>(List1);

Then List2 should be a copy of List1 and any updates made to it should not reflect in the original list.

That being the case, consider the following test code:

public class Fake
{
    public string MyVal { get; set; }
}

public List<Fake> List1;
public List<Fake> List2;

public void UpdateClassTest()
{
    List1 = new List<Fake>() {new Fake() { MyVal = "hello" } };

    List2 = new List<Fake>(List1);
    string propName;

    System.Type type = typeof(Fake);
    foreach (System.Reflection.PropertyInfo pi in type.GetProperties(System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Instance))
    {
        propName = pi.Name;
        List2.ForEach(f => pi.SetValue(f, "Good Bye"));
    }
}

When I run this Both List1[0] and List2[0] get updated to "Good Bye", but I would assume List1 would not be affected by the changes I'm making to List2.

What am I doing wrong or not understanding here?

John Bustos
  • 19,036
  • 17
  • 89
  • 151

2 Answers2

3

new List(List other) does not do a deep copy. When you modify the item at [0] it's modifying the original object, which exists in both lists.

See this other question about implementing ICloneable.

Community
  • 1
  • 1
Sam Trost
  • 2,173
  • 20
  • 26
2

Copying the list means that the lists are different objects. The elements contained by the lists are still the same. For instance:

List1 = new List<Fake>() {new Fake { MyVal = "hello" } };
List2 = new List<Fake>(List1);

List2.Add(new Fake { MyVal = "hey" });
Console.WriteLine(List1.Length); // 1
Console.WriteLine(List2.Length); // 2

List2[0].MyVal = "hi";
Console.WriteLine(List1[0].MyVal) // hi
Fernando Matsumoto
  • 2,697
  • 1
  • 18
  • 24