The Heap and the Stack


Reference types, for example objects are allocated on the heap. When an object is allocated on the heap its address is returned, and that address is assigned to a reference. The garbage collector destroys objects on the stack sometime after the stack frame they are declared within ends.

A stack is a data structure used to store items on a last in first out basis. That means items first entered into stack will come last. The stack refers to an area of memory supported by the processor, on which the local variables are stored. In C#, all value types are allocated on the stack - an area of memory is set aside for their value, and this area is referred to by the name of the variable.

Typically a stack frame is defined by a function. Thus, if you declare a local variable within a method the object will be marked for garbage collection after the method execution ends. Objects on the heap are garbage collected sometime after the final reference to them is destroyed.