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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With