Sometimes when doing interop, you want to have an array embedded inside of a struct. For example, something like:
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:
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:
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:
fixed int values;
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.