Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Array initialization without the keyword "new"

In C# it is possible to initialize an array without the keyword "new" like in the following example:

int[] x = { 10, 20, 30 };

Does this mean that the array will be initialized on the stack since the keyword "new" is necessary to initialize something on the heap?

like image 940
Gerhard Wonner Avatar asked Oct 23 '25 19:10

Gerhard Wonner


1 Answers

Short answer: No.

The code you show is shorthand for int[] x = new [] { 10, 20, 30 }
which is shorthand for int[] x = new int[] { 10, 20, 30}
which is shorthand for int[] x = new int[3]; x[0] = 10; x[1] = 20; x[2] = 30;

(see MSDN)

There is no difference in implementation.

The only way of allocating an array on the stack is using unsafe code with the stackalloc keyword, as pointed out in the comments. Example from MSDN:

int* block = stackalloc int[100];
like image 116
Bas Avatar answered Oct 26 '25 09:10

Bas



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!