Question

in C#, when i declare an array like this:

int []a = {1, 2, 3, 4, 5}

is this declared in the stack ?

from what I know, i should do this:

int []a = new int[5]{1, 2, 3, 4, 5};

Considering that Arrays are reference types.

Était-ce utile?

La solution

There is no difference between those two.

The first one is just a syntactic sugar (MSDN) to save several keystrokes.

They both (as long as both are identical arrays) are declared in the heap, and the reference is declared in the stack. So as long as you go out of scope - so the object becomes unreferenced and eligible for being garbage collected.

Autres conseils

There is actually a way to store arrays in the stack:

(From http://www.c-sharpcorner.com/uploadfile/GemingLeader/creating-a-stack-based-array/)

int* pArr = stackalloc int[length];

But this requires an unsafe code region, due to use of pointers.

both of you syntax will declare on heap as ints are value type

int[] a = {1, 2, 3, 4, 5 } this syntax is a slight shorthand of the other

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top