John Z. Li
John Z. Li

Reputation: 1995

Initialize an array of struct in C#

First of all, this question is not a duplicate of this one or this one. I am not looking for answers taking the form of

Some_struct[] struct_array = new[]{
    Some_struct(parameters),
    Some_struct(parameters),
    ...
}

with Some_struct has a parameterized constructor.

The array to be created is large in size. Is there a way that one can initialize the array all at once without iterating over its indexes and explicitly initializing each data member?

Upvotes: 0

Views: 1309

Answers (1)

Tim Schmelter
Tim Schmelter

Reputation: 460108

If you need to pass parameters you need a constructor. Otherwise you can simply use:

var array = new Some_struct[1000000];

Since structs are value types, they are all initialized with the default values.

Some_struct s = array[4711]; // never null

Upvotes: 2

Related Questions