To fully understand how memory is managed in the .NET Framework you need to
understand the difference between the Stack and the Heap. This lesson introduces
you to those differences and how it affects your development.
- Variables that are directly managed on the Stack (or Call Stack) are called
Value Types.
- Variables that are managed on the Heap are called Reference Types.
The Stack (Value Types)
Value Types are data types that are directly managed on the stack. This means
that when a variable is declared it directly contains its data on the stack.
Value Types include...
- Integral types
- sbyte
- byte
- short
- ushort
- int
- uint
- long
- ulong
- Floating Point types
- Decimal type
- Boolean type
- Enumerations
- any enumeration created using "enum"
- Structures
- user defined datatype created using "struct"
The following code sample shows that Value Types directly contain their own
data.
static void Main(string[] args)
{
int i; i = 5;
int j; j = i;
j++;
}
The Heap (Reference Types)
Reference Types are managed on the heap. This means that when a variable is
declared, the stack receives a reference to the memory on the heap. In other
word, the variable does not directly contain its own data on the stack.
Reference Types include...
- All objects that are created usng "class"
The following code sample show that Reference Types do not directly contain
their own data.
static void Main(string[] args)
{
ArrayList list1; list1 = new
ArrayList();
list1.Add(5);
ArrayList list2; span class="comment">//this
declaration allocaties memory on the stack
list2 = list1;
list2.Add(6);
}
So why is it important to understand the differences between how memory is
managed on the stack and on the heap?
Memory that is allocated on the stack is released immediately when it is no
longer referenced. However, memory that is allocated on the heap is not released
immediately when it is no longer referenced. Garbage Collection is used to
ensure that memory on the heap is released occasionally. See Intro to Garbage
Collection for more information.