Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Instantiating Array and Instantiating each Member at once

Consider the following case:

ColumnDefinition[] columns = new ColumnDefinition[2];
columns[0] = new ColumnDefinition();
columns[1] = new ColumnDefinition();

After instantiating columns as an array of ColumnDefinition, I needed to explicitly instantiate each array element. Of course, it could have been done using loops, but I was wondering if there was something simpler which would instantiate every element at once after instantiating the Array type itself.

like image 943
Shamim Hafiz - MSFT Avatar asked Dec 12 '25 17:12

Shamim Hafiz - MSFT


2 Answers

You can apply a little LINQ:

var columns = Enumerable.Repeat(new ColumnDefinition(), 10).ToArray();

Adjust the count passed to Repeat for the size of array. However this will lead to the same object being saved in each element of the array. So maybe the creation needs to be repeated:

var columns = Enumerable.Repeat(0, 10).Select(i => new ColumnDefinition()).ToArray();
like image 198
Richard Avatar answered Dec 14 '25 06:12

Richard


var columns = new []{new ColumnDefinition(), new ColumnDefinition()};

Works as expected.

like image 31
BitKFu Avatar answered Dec 14 '25 08:12

BitKFu



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!