How does C# handle arrays of struct – do I need to allocate each array element (as if it was an array of class objects)?
Example:
public struct RGBA { public byte red, green, blue, alpha; }
public RGBA [] colorBuffer = new RGBA [1024*1024];
Now is colorBuffer an array of pointers to RGBA objects, and do I have to allocate them, e.g. like this:
for (int i = 0; i < colorBuffer.Length; i++)
colorBuffer [i] = new RGBA ();
or does colorBuffer point to a memory chunk of 4 MB in size, containing 1 MB RGBA structs?
The
colorBuffervariable value will be a reference to the array object. The array object itself will be a single object, 4MB in size (4 bytes * 1024 * 1024). The array is a reference type, but each element is a value type. The element value is the RGBA value – it’s not a pointer.The array will be initialized to
default(RGBA)for each element automatically, do you don’t need to perform your own initialization.If you do:
that’s just copying a reference – the two variables now refer to the same array.