In the following code, a struct is obtained from an array and from a list. When getting the item by index, the array appears to do it by reference whereas the list appears to do it by value. Can someone explain the reasoning behind this?
struct FloatPoint {
public FloatPoint (float x, float y, float z) {
this.x = x;
this.y = y;
this.z = z;
}
public float x, y, z;
}
class Test {
public static int Main (string[] args) {
FloatPoint[] points1 = { new FloatPoint(1, 2, 3) };
var points2 = new System.Collections.Generic.List<FloatPoint>();
points2.Add(new FloatPoint(1, 2, 3));
points1[0].x = 0; // not an error
points2[0].x = 0; // compile error
return 0;
}
}
Changing the struct definition to a class makes both compile.
When you get a struct, it is always by value. The structure will be copied, you don’t get a reference to it.
The difference is that you can access the sctruct directly in the array, but not in the list. When you change the property in the struct in the array, you access the property directly, but to do the same with a list you have to get the struct, set the property, then store the struct back in the list:
Earlier versions of the compiler would let you write the code that you have, but for a list it would generate code similar to this:
I.e. it would read the struct, change it, and silently throw the changed struct away. The compiler was changed to give an error in that case.