Claudi Claudi - 1 month ago 9
C# Question

How to populate array of structs, without using a line for code for each member?

I'm currently trying to find a better way to populate an array of structs.
first off, this is the data going in to making my struct

enum DataType
{
Uint8, Uint16, Byte, Int16, Int32,
TypeSatInfo, TypeCell, ByteArray
}
enum ReadWriteState
{
ReadWrite, ReadOnly, WriteOnly
}
struct Parameter
{
public string ParamName;
public short ParamId;
public DataType Datatype;
public ReadWriteState ReadWrite;

}


Then I have a class which should hold my populated array

static class Parameters
{
public static Parameter[] Param = new Parameter[80];
}


and the last part I have is the function, which I want to use to populate the array.

void populateParameters()
{
Parameters.Param[0].ParamName = "RevProtocol";
Parameters.Param[0].ParamId = 0x0001;
Parameters.Param[0].Datatype = DataType.Uint16;
Parameters.Param[0].ReadWrite = ReadWriteState.ReadOnly;

Parameters.Param[1].ParamName = "HwProtocol";
Parameters.Param[1].ParamId = 0x0002;
Parameters.Param[1].Datatype = DataType.Uint16;
Parameters.Param[1].ReadWrite = ReadWriteState.ReadOnly;

//keep this going until array is full.
}


I was hoping to do something like:

Parameters.Param[80] = {{"RevProtocol", 0x0001, DataType.Uint16, ReadWriteState.ReadOnly},
{"HwProtocol", 0x0002, DataType.Uint16, ReadWriteState.ReadOnly}}


By doing like this i hope to be able to populate the entire array at once, but i cant seem to find the right syntax for this. Is something like this possible?

Answer

You are close. When using the object and collection initializers you still need to use the new keywords:

Parameters.Param = new Parameter[]
{
    new Parameter { ParamId = 0x0001, ParamName = "RevProtocol", Datatype = DataType.Byte },
    new Parameter { ParamId = 0x0002, ParamName = "HwProtocol", Datatype = DataType.TypeCell },
};

See in more details in the Object and Collection Initializers (C# Programming Guide)