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!!
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With