ECMA-334: 12.1.7 Local variables

Microsoft .NET Framework, ASP.NET, Visual C# (CSharp, C Sharp, C-Sharp) Developer Training, Visual Studio


Jump to: navigation, search
C# Language Specification
© 2006 ECMA International

12.1.7 Local variables

A local variable is declared by a local-variable-declaration, foreach-statement, or specific-catch-clause of 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 initially assigned.

A local-variable-declaration can occur in a block, a for-statement, a switch-block, 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 scope with which it is associated, at least until execution of that scope ends in some way. (Entering an enclosed block, calling a method, or yielding a value from an iterator block suspends, but does not end, execution of the current scope.) If the local variable is captured by an anonymous method, the lifetime of the variable is extended at least until all referencing delegates are eligible for garbage collection (§14.5.15.3.1). If the parent scope is entered recursively or iteratively, a new instance of the local variable is created each time, and its local-variable-initializer, if any, is evaluated each time. [Note: A local variable is instantiated each time its scope is entered. This behavior is visible to user code containing anonymous methods. end note]

A local variable introduced by a local-variable-declaration is not automatically initialized and thus has no default value. Such a local variable is considered initially unassigned. A local-variable-declaration can 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.

[Note: The actual lifetime of a local variable is implementation-dependent. For example, a compiler might statically determine that a local variable in a block is only used for a small portion of that block. Using this analysis, the compiler could generate code that results in the variable’s storage having a shorter lifetime than its containing block.

The storage referred to by a local reference variable is reclaimed independently of the lifetime of that local reference variable (§10.9). end note]


Today's Deals: Electronics

Personal tools