Local Variables

Local Variables

Local variables are objects declared in a statement block. Local variables can be declared anywhere in the block, but must be defined before use. Local variables can be either value or reference types. A value type is allocated storage on the stack, whereas reference types have memory allocated on the managed heap. The storage for value types is released deterministically at the end of a statement block. Reference types are allocated with the new keyword and removed nondeterministically by the Garbage Collector, which is a component of the Common Language Runtime (CLR).

Variables can be declared with or without the assignment operator and they can be declared without being initialized. That is not a good practice, however. Use the assignment operator to declare and initialize a variable. Variables can be declared in a single declaration statement individually or by daisy-chaining the variable names:

int variablea=5, variableb, variablec=10;

The scope and visibility of a local variable is the statement block, where it is declared, and any nested statement blocks. This is called the variable declaration space, in which local variables must be uniquely identified.

A variable that is not to be modified at run time should be const. (Const variables must be initialized at compile time and cannot be changed later at run time.)

In the following code, several local variables are defined. The storage for variablea, variableb, variablec, and variabled are released at the end of the function block. However, the lifetime of variablee, a local variable, is managed by the Garbage Collector. Setting variablee to null is a hint to the Garbage Collector that the object is no longer required, and that it should hasten cleanup:

void Function() {
    int variablea=0;
    int variableb=1,variablec, variabled=4;
    const double PI=3.1415;
    UserDefined variablee=new UserDefined();

    / function code