double
is a value type whereas double[]
is a reference type, and when you pass a value type to a variable, or into a method, etc.. it will copy the value. When you pass a reference type to a method it will copy the reference but not the underlying value. Ultimately you will have multiple references to the same object.
The issue that you're seeing here is that you have two lists where the first element refers to the same array instance in memory. If you want to change values to an array then you'll need to create a shallow copy of it. A shallow copy means that the array itself will be cloned, but the items within the array will remain the same.
Once you've cloned your array you can alter the values in the new array all you like and it won't affect the original array. Here's a snippet to demonstrate the issue you're noticing & also how you can fix it:
Without the cloning:
{
double[] arr = new[] { 0.5 };
List<double[]> list1 = new() { arr };
List<double[]> list2 = new() { arr };
// This affects both list1 and list2 because they hold the *same* "double[]"
// in their first elements.
list1[0][0] = 0.2;
Console.WriteLine(list2[0][0]);
}
Prints: 0.2
With the cloning:
{
double[] arr = new[] { 0.5 };
List<double[]> list1 = new() { (double[])arr.Clone() };
List<double[]> list2 = new() { (double[])arr.Clone() };
// This only affects the clone in list1, leaving list2 and the underlying original array unaffected
// in their first elements.
list1[0][0] = 0.2;
Console.WriteLine(list2[0][0]);
}
Prints: 0.5
No problem - happy to help