Yesterday I started a preperation course for Microsofts 70-536 exam (application development foundation). It is the first part of Microsoft’s MCTS in ASP.NET, which I plan to finish during 2010. Even though a lot of the curriculum is fairly basic, it is still very interesting stuff. It turns out that there are a lot of things that I didn’t know about the framework and how it fundamentally works. I figured that the stuff that I find interesting might be interesting for others too and therefore I’ve decided to write a few posts about the stuff that we cover in the course.

This blog post is about some of the inner workings of .NET: the stack and the heap. Most programmers have a fairly good idea about what it is – but what is the actual difference between the two? And how are they used?

Basically both the heap and the stack are memory that .NET uses for the different variables and objects. The stack is a memory block which only contains variables that have a constant size – also called value types. Int, double and Booleans are all value types, because they all have a fixed size (32 bits, 64 bits and 1 bit byte). Strings are not a value type. This is because a string does not have a predefined length and therefore the stack does not know how much space is required to store the string. String and all other classes are reference types. They are called reference types, because they are characterized by having a reference on the stack to the place on the heap.

The heap holds all of our objects and is a much more dynamic type of memory than the stack. The main difference between the two is that the stack is much faster than the heap. It is not slower to access objects in the heap than on the stack as such – but the overhead required to maintain the heap. The maintenance of the heap is called garbage collection and is the operation of going through the objects in the heap, removing all the objects that no longer have a reference in the stack and refragmenting the memory.

A small twist to the types that can be stored on the stack, is that structures also can be stored on the stack - but only if the structure only contains value types. For instance is System.Drawing.Point is a value type. It represents an ordered pair of integer x- and y-coordinates that defines a point in a two dimensional plane. The structure does not contain any reference types and therefore it is also a value type.