When I use an array of struct
s (for example System.Drawing.Point), I can get item by index and change it.
For example (This code work fine):
<
This is because for the array points[i]
shows where the object is located. In other words, basically points[i]
for an array is a pointer in memory. You thus perform operations on-the-record in memory, not on some copy.
This is not the case for List
: it uses an array internally, but communicates through methods resulting in the fact that these methods will copy the values out of the internal array, and evidently modifying these copies does not make much sense: you immediately forget about them since you do not write the copy back to the internal array.
A way to solve this problem is, as the compiler suggests:
(3,11): error CS1612: Cannot modify a value type return value of `System.Collections.Generic.List.this[int]'. Consider storing the value in a temporary variable
So you could use the following "trick":
List points = new List { new Point(0,0), new Point(1,1), new Point(2,2) };
for (int i = 0; i < points.Count; i++) {
Point p = points[i];
p.X += 1;
points[i] = p;
}
So you read the copy into a temporary variable, modify the copy, and write it back to the List
.