Differences between arrays and lists using structures

In the following code, the structure is obtained from an array and from a list. When you get an item by index, the array seems to do it by reference, while the list seems to do it by value. Can someone explain the reasons for 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 structure definition for a class does compilation.

+4
source share
1 answer

When you get a structure, it is always by value. The structure will be copied, you will not receive a link to it.

The difference is that you can access sctruct directly in the array, but not in the list. When you change a property in an array structure, you access the property directly, but in order to do the same with the list, you must get the structure, set the property, and then save the structure in the list:

 FloatPoint f = points2[0]; fx = 0; points2[0] = f; 

Earlier versions of the compiler will allow you to write the code that you have, but for a list, it will generate code similar to this:

 FloatPoint f = points2[0]; fx = 0; 

those. he will read the structure, change it and quietly throw away the changed structure. The compiler has been modified to give an error in this case.

+6
source

All Articles