List<Box[]> boxesList = new List<Box[]>(); // create a new list that contains boxes
Box[] boxes = new Box[9]; // create an array of boxes
boxesList.Add(boxes); // add the boxes to the list
boxesList[0][0] = new Box(2, new Point(0, 0)); // change the content of the list
boxes[0] = new Box(1,new Point(0,0)); // change content of the boxarray
The problem is after initializing the first
element of the boxes array. The boxesList is also changed.
I think the problem is that the box
array is stored as a reference in the list.
Is there a way around this?
So that the boxeslist will not be changed by changing the box array
No, it’s not. The
boxesListhas exactly the same contents as it had before: a reference to the array of boxes. There’s only one array here. If you change it, whether that’s throughboxesList[0]orboxes, you’re changing the same array.If you want to take a copy of the array, you need to do so explicitly. It’s up to you whether you create a copy of the array and put the reference to the copy in the list, or copy the array afterwards.
See my article on reference types and value types for more information, remembering that all array types are reference types.