1

I can't understand why the value of my list changes when I recalculated the variable used to input the value in the list.

Look's an example.

List<double[]> myList = new List<double[]>();
double[] a = new double[3];

a[0] = 1;
a[1] = 2;
a[2] = 3;
myList.Add(a); // Ok List[1] = 1 2 3

a[0] = 4;      // List[1] = 4 2 3
a[1] = 5;      // List[1] = 4 5 3
a[2] = 6;      // List[1] = 4 5 6
myList.Add(a); // List[1] = 4 5 6 and List[2] = 4 5 6

Can someone help me?

BrunoLM
  • 97,872
  • 84
  • 296
  • 452

1 Answers1

6

The double[] type is the reference type - What is the difference between a reference type and value type in c#?. So, when you add it into the List twice you actually add the same array twice.

a[0] before myList.Add(a); and after will change the same array - List.Add method does not create copy of the value you provide to it.

You should use new array each time or make a copy of it:

List<double[]> myList = new List<double[]>();
double[] a = new double[3];

a[0] = 1;
a[1] = 2;
a[2] = 3;
myList.Add(a); // Ok List[0] = 1 2 3

a = new double[3];
a[0] = 4;      // List[0] = 4 2 3
a[1] = 5;      // List[0] = 4 5 3
a[2] = 6;      // List[0] = 4 5 6
myList.Add(a); // List[0] = 1 2 3 and List[1] = 4 5 6
Community
  • 1
  • 1
Eugene Podskal
  • 10,270
  • 5
  • 31
  • 53