Copying a list of lists of int's in c#
Hello, I'm having a bit of trouble with lists, mainly I want to copy contents of one list to another one without leaving any connection between them. But for some reason I'm not able to do that, I've noticed that this happens only with lists of lists. Thanks for any help
List<int> A = new List<int> ();
List < List<int>>B= new List < List<int>>();
List < List<int>>D= new List < List<int>>();
void Start () {
A.Add (3);
A.Add (4);
A.Add (5);
B.Add (new List<int> (A));
D = new List<List<int>> (B); //why new doesn't mean new?
B [0] [1] = 7;
print (D [0] [1]); //prints 7 and I want 4
}
}
Answer by NerdClown · Sep 13, 2016 at 11:43 AM
//why new doesn't mean new?
I believe the answer to this has to do with references. List B contains REFERENCES to its elements (just one element at this point, namely list A). So when you ask for a new List B, it will make you a brand new list (because you ask for it), but the content of the list will be copied, i.e. the references are copied but still reference the same elements. This is why changing the element in D will also change the element in B.
Anyhow, I guess THIS explains it better!
Yeah
D = new List<List<int>> (B);
DOES create a new list, but the content of that list is the actual list B you created earlier and feed in as the parameter here.
Change it to
D = new List<List<int>> (new List<int>(A));
and it should work as you describe. Now your list of lists will contain a new list with the same content as A. Int is a value type so the values in A will not change when you change some int in this new list of ints. The values of ints in list A are copied to the new list, not references to those ints.
Your answer
Follow this Question
Related Questions
Why is my List adding to same array object again and again in update? 1 Answer
Endless Runner with new Biome each time 0 Answers
Increase List of Spawns Dynamically 1 Answer
All crops in list growing at once when they are supposed to grow individually 0 Answers
Trying to program two buttons to appear when the player in my game dies 0 Answers