When is array allocated on stack in c#? When is array allocated on stack in c#? arrays arrays

When is array allocated on stack in c#?


10 int structs would be allocated on the the heap, only pointer to them would be on stack, correct?

Yes, correct.

How would one make fixed size array to go on stack? What if I'm using stucts I defined?

The stackalloc keyword serves this purpose. However, this works in unsafe context only, which is a rather unnecessarily limiting factor in most scenarios, not worth the performance tradeoff.

Example:

public void unsafe foo(){    int* bar = stackalloc int [10];}

You will have to use pointer arithmetic to access members of the array.

What if I want array size passed as parameter to function? As far as I understand there should be no problem to get array of arbitrary size on stack when function is called, if size is known when function is called.

Works as expected:

public void unsafe foo(int length){    int* bar = stackalloc int [length];}

Should I even be bothered by this? As far as I understand getting this fixed size array on stack would improve performance, because no heap allocation is done.

No, in general not. Unless you deal with some very specific performance-critical scenarios, like heavy math computations, encryption, compression etc., it brings no real benefit.

Also, see this question for performance-related discussion.