Variables and Parameters
A variable represents a storage location that has a modifiable value. A variable can be a local variable, parameter (value, ref, or out), field (instance or static), or array element.
The Stack and the Heap
The stack and the heap are the places where variables and constants reside. Each has very different lifetime semantics.
Stack
The stack is a block of memory for storing local variables and parameters. The stack logically grows and shrinks as a function is entered and exited. Consider the following method (to avoid distraction, input argument checking is ignored):
static int Factorial (int x)
{
if (x == 0) return 1;
return x * Factorial (x-1);
}This method is recursive, meaning that it calls itself. Each
time the method is entered, a new int is allocated on the stack, and each time
the method exits, the int is
deallocated.
Heap
The heap is a block of memory in which objects (i.e., reference-type instances) reside. Whenever a new object is created, it is allocated on the heap, and a reference to that object is returned. During a program’s execution, the heap starts filling up as new objects are created. The runtime has a garbage collector that periodically deallocates objects from the heap, so your computer does not run out of memory. An object is eligible for deallocation as soon as it’s not referenced by anything that’s itself alive.
Value-type instances (and object references) live wherever the variable was declared. If the instance was declared as a field within ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access