Make a copy:
testList.Add(testArray.ToArray());
Frage
Is there a way to add an array to a list of arrays by value and not by reference?
Example: The following prints out "6, 7, 8, 9, 10". I want it to write out "1, 2, 3, 4, 5".
int[] testArray = new int[5] { 1, 2, 3, 4, 5 };
List<int[]> testList = new List<int[]>();
testList.Add(testArray);
testArray[0] = 6;
testArray[1] = 7;
testArray[2] = 8;
testArray[3] = 9;
testArray[4] = 10;
foreach(int[] array in testList)
{
Console.WriteLine("{0}, {1}, {2}, {3}, {4}", array[0], array[1], array[2], array[3], array[4]);
}
Lösung
Make a copy:
testList.Add(testArray.ToArray());
Andere Tipps
You have to Clone()
the array i.e. create shallow copy of array and add that in the list.
testList.Add((int[])testArray.Clone());
Instead of
testList.Add(testArray);
use
testList.Add(testArray.Clone() as int[]);