asdrubael
asdrubael

Reputation: 483

Filling a C# struct array with multiple values at once

I have a struct array which looks like this:

    public struct DATA
    {
        public int number;
        public int channel;
        public string filename;
        public string description;
    }
    DATA[] myData = new DATA[12];

I need to fill a lot of values in here, for example myData[0] = {0, 1, "myfile", "TBD"} etc.

What is the easiest way (in terms of LOC) to fill these 12 structs with data? Would it be easier to use a class instead?

Upvotes: 4

Views: 17275

Answers (3)

matthias.lukaszek
matthias.lukaszek

Reputation: 2220

The C method to do this doesn't work.

DATA[] myData = new DATA[]{{1,3,"asdasd","asdasd"}, {...

You have to set every single DATA struct.

I suggest to add a constructor

public DATA(int number, int channel, string filename, string description)
{
    this.number = number;
    this.channel = channel;
    this.filename = filename;
    this.description = description;
}

and fill the array using the ctor

DATA[] myData = new DATA[]{
    new DATA(1,  3,  "abc",  "def"),
    new DATA(2, 33, "abcd", "defg"),
    ...
};

You can also use a generic list and initilize it this way (.NET 3.5 and later):

List<DATA> list = new List<DATA>()
{
    new DATA(1,  3,  "abc",  "def"),
    new DATA(2, 33, "abcd", "defg")
};

Upvotes: 5

SwDevMan81
SwDevMan81

Reputation: 49988

A simple for loop will probably work best:

 for (int i = 0; i < myData.Length; i++)
 {
    myData[i] = new DATA() { number = i, channel = i + 1, filename = "TMP", description = "TBD"};
 }

Upvotes: 0

Lloyd
Lloyd

Reputation: 29668

You can have a constructor for a struct:

 public struct DATA
    {
        public int number;
        public int channel;
        public string filename;
        public string description;

        public DATA(int theNumber, int theChannel, ...)
        {
           number = theNumber;
           channel = theChannel;
           ...
        }

    }

You might then also find a List more useful:

List<DATA> list = new List<DATA>();

list.Add(new DATA(1,2,...));

Then:

DATA[] data = list.ToArray();

Upvotes: 2

Related Questions