How do I initialize an array of structs within a struct in C#?
public const int MAX_AXIS = 10;
struct realprm
{ /* real parameter */
long prm_val; /* value of variable */
long dec_val; /* number of places of decimals */
};
[StructLayout(LayoutKind.Explicit)]
unsafe struct iodbpsd
{
[FieldOffset(0)] short datano; /* parameter number */
[FieldOffset(2)] short type; /* upper byte:type */
/* lower byte:axis */{
[FieldOffset(4)] char cdata; /* bit/byte parameter */
[FieldOffset(4)] short idata; /* word parameter */
[FieldOffset(4)] long ldata; /* 2-word parameter */
[FieldOffset(4)] realprm rdata; /* real parameter */
[FieldOffset(4)] fixed char cdatas[MAX_AXIS];/*bit/byte parameter with axis*/
[FieldOffset(4)] fixed short idatas[MAX_AXIS];/* word parameter with axis */
[FieldOffset(4)] fixed long ldatas[MAX_AXIS];/* 2-word parameter with axis */
[FieldOffset(4)] realprm rdatas[MAX_AXIS];/* real parameter with axis */
};
The last entry, realprm, throws compiler errors:
CS0270 Array size cannot be specified in a variable declaration (try initializing with a 'new' expression)
CS0650 Bad array declarator: To declare a managed array the rank specifier precedes the variable's identifier. To declare a fixed size buffer field, use the fixed keyword before the field type.
The 'fixed' keyword won't work for structs, and C# does not allow 'new' keyword initialization:
CS0573 Field declaration: cannot have instance field initializers in structs
Is there any elegant way to initialize an array like this in C#?
fixed byte rdatas[MAX_AXIS * sizeof(realprm)], accessing to such array elements can be done via helper methods.