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?

2
  • 1
    I strongly suggest to read this. Then you'll understand why that happens. Commented Aug 16, 2014 at 14:05
  • 1
    You add the same instance of a to the list twice.... Commented Aug 16, 2014 at 14:05

1 Answer 1

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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.