Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Initialization of const array of struct

Tags:

c#

How do I do a constant initialization an array of a structure type? For example, in C I would do something like this:

struct Item {
    int a;
    char const * b;
};
Item items[] = {
    { 12, "Hello" },
    { 13, "Bye" },
};

I've been looking at various C# references but can't find an equivalent syntax. Is there one?

like image 881
edA-qa mort-ora-y Avatar asked May 08 '14 06:05

edA-qa mort-ora-y


Video Answer


1 Answers

Sample code:

struct Item
{
    public int a;
    public string b;
};
Item[] items = {
    new Item { a = 12, b = "Hello" },
    new Item { a = 13, b = "Bye" }
};

Additional option to introduce parametrized constructor:

struct Item
{
    public int a;
    public string b;

    public Item(int a, string b)
    {
        this.a = a;
        this.b = b;
    }
};
Item[] items = {
    new Item( 12, "Hello" ),
    new Item( 13, "Bye" )
};

As @YoYo suggested, removed new[] part.

Tricky way (for the case where new Item bothers you much)

Declare new class:

class Items : List<Item>
{
    public void Add(int a, string b)
    {
        Add(new Item(a, b));
    }
}

Then you can initialize it as:

Items items = new Items {
    { 12, "Hello" },
    { 13, "Bye" }
};

You can also apply .ToArray method of List to get an array of Items.

Item[] items = new Items {
    { 12, "Hello" },
    { 13, "Bye" }
}.ToArray();

The trick is based on collection initializers (http://msdn.microsoft.com/en-us/library/bb384062.aspx):

By using a collection initializer you do not have to specify multiple calls to the Add method of the class in your source code; the compiler adds the calls.

like image 143
Ulugbek Umirov Avatar answered Oct 26 '22 22:10

Ulugbek Umirov