Memory Allocation: The Stack Versus the Heap
Objects created within methods are called local variables, as we discussed earlier. They are local to the method, as opposed to belonging to the whole object, as member variables are. The object is created within the method, used within the method, and then destroyed sometime after the method ends. Local objects are not part of the object’s state—they are temporary value holders, useful only within the particular method.
Local variables of intrinsic types such as int
are created on a portion of memory known as the stack. The stack is allocated and de-allocated as methods are invoked. When you start a method, all its local variables are created on the stack. When the method ends, local variables are destroyed.
These variables are referred to as local because they exist (and are visible) only during the lifetime of the method. They are said to have local scope. When the method ends, the variable goes out of scope and is destroyed.
C# divides the world of types into value types and reference types. Value types are created on the stack. All the intrinsic types (int, long
) are value types (as are structs, discussed later in this chapter), and thus are created on the stack.
Objects, on the other hand, are reference types. Reference types are created on an undifferentiated block of memory known as the heap. When you declare an instance of a reference type, what you are actually declaring is a reference, which is a variable that refers to another ...
Get Learning C# 3.0 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.