Arrays inside of structures

Sometimes when doing interop, you want to have an array embedded inside of a struct. For example, something like:

struct data
{
    int header;
    int values[10];
}

that you either used in a call to interop, or with unsafe code to deal with an existing format - something like a network packet or a disk record.

You can do this in current versions of C#, but it's ugly. The most obvious way is:

struct Data
{
    int header;
    int value0;
    int value1;
    int value2;
    int value3;
    int value4;
    int value5;
    int value6;
    int value7;
    int value8;
    int value9;
}

But that's a bit ungainly, though, you *can* take the address of value0 and then use pointer arithmetic to access the various "array elements". There's a somewhat shorter version:

[StructLayout(LayoutKind.Sequential, Size=44)]
struct data
{
    int header;
    int values;
}

Setting the size to be 44. If you want to have more than one such array or have fields after the first one, you'll need to use LayoutKind.Explicit and put a FieldOffset attribute on every field.

In either case, you access the "array" by getting a pointer to the values field, and using pointer arithmetic.

To make this a little cleaner and less error-prone, in C# 2.0 we've added a fixed array syntax, allowing you to write:

struct data
{
    int header;
    fixed int values[10];
}

and getting the exact same behavior. You can then treat values as if it's a "c-style" array, using indexing, etc.

Because the underlying implementation is still using pointers and there's the possibility of going outside the allocated space, code generated using this feature requires using "unsafe", and therefore requires elevated privilege to execute.