Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Initializing few specific values in an array, set rest to default

Is there a way to declare an array with 60 values like this (few specific values, the rest will be calculated later on):

long[] l = { 1, 2, new long[58] };

instead of having to waste 2 lines for something like this:

long[] l = new long[60];
l[0] = 1;
l[1] = 2;
like image 317
Tomas Loksa Avatar asked Jan 30 '26 21:01

Tomas Loksa


1 Answers

You can initialize the full array (which would give all elements default value), and then use Array.Copy to only populate part of it from a fixed, shorter array:

int[] arr = new int[60];
Array.Copy(new[] {1, 2, 3}, arr, 3);

A more extravagant (and wasteful) method would be to use LINQ:

int[] arr = new[] {1, 2, 3}.Concat(Enumerable.Repeat(0, 57)).ToArray();

There's another funny way based on the Array API, and that is to resize the small array to fit the large size. This process will assign all new elements the default value:

int[] arr = new[] {1, 2, 3};
Array.Resize(ref arr, 60);
like image 79
Zoran Horvat Avatar answered Feb 01 '26 09:02

Zoran Horvat



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!