Objects created within methods are called local variables . They are local to the method, as opposed to belonging to the object, as member variables do. The object is created within the method, used within the method, and then destroyed when 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
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 the 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 (
long) are value types (as are structs,
discussed later in the chapter), and thus are created on the
Classes, 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 object. The reference acts like ...