4.1.1.13–4.1.1.14 - Local and global variable scope (C#)
Learn where variables can be accessed, how long a subroutine's local state lasts, and why explicit parameters and return values usually make dependencies easier to control.
This C# route is incomplete: runnable support pending. Work with the native written examples and questions; no Run is provided.
Lifetime and visibility
Scope concerns where a variable's name can be used; lifetime concerns when its storage exists. A local variable declared inside a method belongs to that invocation of the method. In the simple non-captured methods used here, its state exists only while the method executes, and code outside that method cannot access it by name.
static int NextValue(int start)
{
int result = start + 1;
return result;
}
// Inside Main:
int result = 20;
Console.WriteLine(NextValue(4)); // 5
Console.WriteLine(result); // 20
The parameter start and local result belong to NextValue. Main's result is a separate variable, even though it has the same spelling. Returning 5 copies that value to the calling expression; it does not grant access to the local variable. A later call creates another set of local state. A local declared inside a nested block such as an if or loop has a narrower scope inside that block.
Local variable
A variable declared within a subroutine, accessible only within its permitted local scope. Separate invocations have separate local state.
Parameters supply initial local values. A local must be definitely assigned before C# reads it. For example, int count; Console.WriteLine(count); is invalid, whereas int count = 0; gives a defined starting state.
Local state and side effects
Keeping temporary working state local prevents unrelated methods from accidentally depending on or changing it. Initialise an accumulator inside the method when each call must perform a fresh calculation.
static int Total(int[] values)
{
int sum = 0;
for (int i = 0; i < values.Length; i++)
{
sum = sum + values[i];
}
return sum;
}
Calls with { 2, 5 } and then { 4 } return 7 and 4. sum starts at zero for each call; the second answer is not 11. The method reads the array but does not change it. Repeated calls with the same unchanged input give the same result, making an isolated test straightforward.
Local naming alone does not guarantee absence of side effects, which are observable changes beyond the returned result. A local parameter holding an array reference can still change the caller's array through an element assignment. A method can also write to a file, print, or change an object. Check its operations as well as its declarations.
Continue this lesson.
You’re previewing NovaLearn without an account. Create a free account to read the rest.
Create free account