ECMA-334 C# Language Specification12.1.7: Local variables |
A local variable is declared by a local-variable-declaration
, which may occur in a block, a for-statement
, a switch-statement
, or a using-statement
.
The lifetime of a local variable is the portion of program execution during which storage is guaranteed to be reserved for it. This lifetime extends from entry into the block, for-statement
, switch-statement
, or using-statement
with which it is associated, until execution of that block, for-statement
, switch-statement
, or using-statement
ends in any way. (Entering an enclosed block or calling a method suspends, but does not end, execution of the current block, for-statement
, switch-statement
, or using-statement
.) If the parent block, for-statement
, switch-statement
, or using-statement
is entered recursively, a new instance of the local variable is created each time, and its local-variable-initializer
, if any, is evaluated each time.
A local variable is not automatically initialized and thus has no default value. For the purpose of definite assignment checking, a local variable is considered initially unassigned. A local-variable-declaration
may include a local-variable-initializer
, in which case the variable is considered definitely assigned in its entire scope, except within the expression provided in the local-variable-initializer
.
Within the scope of a local variable, it is a compile-time error to refer to that local variable in a textual position that precedes its local-variable-declarator
.
A local variable is also declared by a foreach-statement
and by a specific-catch-clause
for a try-statement
. For a foreach-statement
, the local variable is an iteration variable (15.8.4). For a specific-catch-clause
, the local variable is an exception variable (15.10). A local variable declared by a foreach-statement
or specific-catch-clause
is considered definitely assigned in its entire scope.