- Home /
Adding object to list add the same object to another list
Hello everyone. I'm currently working with lists and i have a bug that a can't figure out. I have two lists and when i add an item to one it automatically add the same object to the other. here is the code :
v_tempNode = v_actualPosition;
v_tempTarget = v_goWeClickedOn;
v_path.Clear();
v_tempPath.Clear();
v_tempPath.Add(v_tempTarget);
at this point if i debug both my v_path and v_tempPath have .Count = 1, filled with v_tempTarget. Any idea/clue of why this is happening ?
is v_path referencing v_tempPath?
Can you show us how these lists are being instantiated and used?
Answer by Jean-Marcel · Nov 12, 2018 at 09:24 PM
I found the problem : when you work with lists if you do List1 = List2 it doesnt just copy the content of your second list into your first list, your first list BECOME your second list, just like they share the same memory address. If you want to copy the content of a list into another one you have to use a for loop or a foreach loop.
Just so you know, List does have a constructor that can accept another List to copy from. So you don't have to loop through and copy each element yourself. You can just write:
List<$$anonymous$$yClass> list2 = new List<$$anonymous$$yClass>(list1);
And list2 will be populated with the same contents as list1, but you can remove or add items to one without affecting the other.