Where a variable can be seen
A variable exists only inside the block of braces where it was declared. That rule explains most name errors.
Inside and outside
C#
private void Show()
{
int outer = 5;
if (outer > 0)
{
int inner = 10;
outputLabel.Text = (outer + inner).ToString();
}
// inner is not visible here
}The rules in plain words
- A variable declared inside a block is visible only in that block and the blocks nested within it.
- A variable declared in the class but outside a method is visible to every method in the class.
- An inner block may reuse an outer name, which hides the outer value and confuses readers, so avoid it.
Declare late and close. Declare a variable just before you use it, in the smallest block that works. It makes the code easier to read and the lifetime easier to reason about.
Scope often matters because of how objects are stored, which leads to value types compared with reference types.