...

/

Managing Memory with Reference and Value Types

Managing Memory with Reference and Value Types

Learn about reference and value types in C#, their allocation in stack and heap memory, and how to differentiate between them.

Let’s look at reference types in detail. There are two categories of memory: stack memory and heap memory. The stack and heap can be anywhere in physical or virtual memory with modern operating systems.

Stack and heap

Stack memory is faster to work with (because it is managed directly by the CPU and because it uses a last-in, first-out mechanism, it is more likely to have data in its L1 or L2 cache) but limited in size, while heap memory is slower but much more plentiful.

Press + to interact
Representation of stack and heap
Representation of stack and heap

On Windows, for ARM64, x86, and x64 machines, the default stack size is 11MB. It is 88 MB on a typical modern Linux-based operating system. For example, in a macOS terminal, we can enter the following command to discover that the stack size is limited to 8 ...