Tech moves fast! Stay ahead of the curve with Techopedia!
Join nearly 200,000 subscribers who receive actionable tech insights from Techopedia.
A local variable, in C#, is a type of variable declared by local variable declaration at the beginning of a block the variable is intended to be local to. It can also occur in a for-statement, a switch-statement, a foreach statement, a using statement or a specific-catch statement or using statement.
The local variable declaration explicitly defines the type of the variable that has been declared along with the identifier that names the variable.
A local variable is a type of variable that can be used where the scope and extent of the variable is within the method or statement block in which it is declared. It is used as an iteration variable in the foreach statement, exception variable in the specific-catch clause and resource variable in the using statement. It can also be used as a constant whose value cannot be modified within the method or statement block in which it is declared.
An implicitly typed local variable whose type is inferred by the compiler from the expression on its right is useful in dealing with language integrated queries (LINQ), which return anonymous types in creating a custom type for each LINQ result set.
The memory allocation of a local variable is based on its type. In case of a value-typed local variable (of types like struct, integer, etc.), the entire contents are stored in the stack, whereas the reference typed variable is stored such that its reference portion is in the stack and its contents are in the heap.
An implicitly typed local variable is declared without using .NET type, but with the keyword "var," which assigns the appropriate type. For example, an implicitly typed local variable can be used in a "foreach" statement without declaring its type to iterate a collection.
A local variable should not be referred in the code in a textual position that precedes the declaration statement of that local variable. In addition, there cannot be two or more local variables with the same name within a single block, as this can result in compilation error. Multiple local variables of the same type can be declared and initialized in a single statement.
Within a method of a class that has a local variable named similar to its field, the local variable hides the field while accessing it within the method. It is more efficient to use a local variable than a field.