Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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!!

like image 467
Michael Svendsen Avatar asked Nov 21 '13 11:11

Michael Svendsen


2 Answers

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.

like image 91
DGibbs Avatar answered Nov 08 '22 15:11

DGibbs


You are adding the same instance of the array to both lists, so they point to the same memory structure.

If you want them to be independent then you'd need to clone them; A quick way from the top of my head would be using linq list.Add(array.ToArray()) in one of the lists

like image 9
Sebastian Piu Avatar answered Nov 08 '22 17:11

Sebastian Piu