Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

If an array is used as an element in struct (C#) , where is it stored?

We use struct in C# whenever possible mainly because it is stored on the stack and no objects are created for it. This boosts the performance.

On the other hand, arrays are stored on the heap.

My question is, if I include an array as an element of the struct, something as follows:

struct MotionVector
{
    int[] a;
    int b;
}

Then what will be the consequences. Will that array be stored on stack? Or the performance advantage of using struct will be lost?

like image 976
shahensha Avatar asked Feb 20 '12 10:02

shahensha


2 Answers

Only the pointer to the array will be stored in the stack. The actual array will be stored in the heap.

like image 149
Dhwanil Shah Avatar answered Oct 04 '22 23:10

Dhwanil Shah


int[] a is a reference type i.e. it references an array of integers. The 'reference' itself will be stored on the stack. However, the data it references will be stored on the heap when you do something like this:

MotionVector z;
z.a = new int[10];
like image 40
Rohan Prabhu Avatar answered Oct 04 '22 22:10

Rohan Prabhu