C# "funny" issues with List<String[]>

arrays, c#, inheritance, list

Solution

`String[] array;` is a reference type. You have added a reference to the location in memory of this object to both lists, therefore they both hold the same data.

If you need the second list to have a copy of the `array` then you can use Array.Copy:

List<String[]> MyPrimaryList = new List<String[]>();
List<String[]> MySecondaryList = new List<String[]>();

String arrayList = "one,two,three,four,five";
String[] array = arrayList.Split(',');
String[] array2 = new string[5];

Array.Copy(array, array2, 5);

MyPrimaryList.Add(array);
MySecondaryList.Add(array2);

MyPrimaryList[0][0] += "half";

Console.WriteLine(MyPrimaryList[0][0]);
Console.WriteLine(MySecondaryList[0][0]);

This takes the source array, a destination array and length - be careful to check the array bounds.

This outputs:

onehalf
one

Since each list now holds a reference to a different array, you can manipulate the array items independently.

Problem

I have some weird issues with List in my C# app. It must be an allocation mistake or that I'm doing something wrong (I'm average C# developer). Let me give an example close to my lines: ``` List<String[]> MyPrimaryList = new List<String[]>(); List<String[]> MySecondaryList = new List<String[]>(); String[] array; String arrayList = "one,two,three,four,five"; array = arrayList.Split(','); MyPrimaryList.Add(array); MySecondaryList.Add(array); MyPrimaryList[0][0] += "half"; ``` So now I would expect first value in the first array in MyPrimaryList to be "onehalf" and "one" in MySecondaryList. But my issue/problem is that both lists gets updated with "onehalf" as first value in the first array in both lists. Do you have a good explanation? :) THANKS!!

Original source