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 automatically 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 nothing references it. In the following example, the StringBuilder
object is created on the heap, while the
sb
reference is created on the stack:
static void Test() { StringBuilder ...
Get C# 3.0 Pocket Reference, 2nd Edition now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.