This page contains general knowledge about the stack and heap and how various data types, ,references and objects are stored in the memory
Stack and Heap in C#
Stack
The stack is a region of memory where data is stored in a last-in, first-out (LIFO) order. In C#, the stack is used for:
- Value types: This includes primitive types like
int, float, bool, char, as well as struct types
- Reference variables: The references themselves (not the objects they point to) are stored on the stack
- Method parameters and local variables: These are automatically allocated and deallocated when methods are called and returned from
Key characteristics of stack memory:
- Fast access (more efficient than heap)
- Limited size (can cause stack overflow if too much data is stored)
- Automatic memory management (variables are cleaned up when they go out of scope)
- Thread-specific (each thread gets its own stack)
Heap
The heap is a region of memory used for dynamic memory allocation. In C#, the heap is used for:
- Reference types: Objects created from classes, interfaces, delegates, and arrays
- String data: Although
string is a reference type, it has special behavior (see immutability section)
- Boxing: When value types are converted to reference types (e.g.,
int to object)
Key characteristics of heap memory:
- Slower access than stack
- Much larger size capacity than stack