Say I have a C# struct:
struct Foo{
int mA;
public int A {get {return mA;}}
int mB;
public int B {get {return mB;}}
public Foo(int a, int b)
{
mA = a;
mB = b;
}
}
And then I create and array of Foo’s:
Foo[] foos = new Foo[10];
What happens when I do this?
foos[1] = new Foo(20, 10);
If Foo was a class, the Foo[] would hold a pointer to a Foo object on the heap, and that pointer would be changed to the new Foo object (the old one being left for recycling).
But since structs are value types, would the new Foo(20, 10) just physically overwrite the same memory location previously held by foos[1]?
In practice the memory associated with the relevant array slot is populated by the values. Given your code a small example shows what goes on. Please see comments inline. This is for a release build.
The code above is JIT compiled as follows
So in short, the code loads the constants in registers and then copies values of these registers to the memory associated with the relevant part of the array instance.