Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Array of ValueType in C# goes to Heap or Stack? [duplicate]

Possible Duplicate:
(C#) Arrays, heap and stack and value types

I am trying to study some differences between memory allocation in c#

Let's suppose that I have this instruction:

int[] array = new int[512];

Does the "array" go to the Heap? Or does it reserve 512 integers on Stack?

like image 980
RSort Avatar asked Jul 22 '11 18:07

RSort


1 Answers

The array itself is memory allocated on the heap. People get confused and think value types are always on the stack and this is not always correct.

For example, in this class:

public class X
{
    public int Y;
}

Even though Y is an int (value type), since it is contained in a class (reference type), the int Y will be stored with the object itself, which is most likely on the heap.

The array is similar. The ints are contained in the array as value types, but the array itself is on the heap, and thus the ints are too.

like image 84
James Michael Hare Avatar answered Oct 20 '22 13:10

James Michael Hare