C#
Variable scope
Learn the scope and visibility rules of variables inside blocks.
Variable scope
A variable's scope is the region where you can reach it. In C# scope is limited by the block where the variable is declared.
A block is the area between curly braces { }. A variable cannot be reached outside the block where it was declared.
Example: if (true) { int bonus = 10; } — here bonus is visible only inside the if block; outside it cannot be used.
However, a variable declared in an outer block can be reached from an inner block. The rule is "visible inside, hidden outside".
Lifetime
A variable's lifetime is how long it lives in memory. Lifetime lasts until the block where it was declared ends.
When the block closes the variable is cleared from memory and cannot be used again. Example: an int i declared inside a for loop is gone when the loop ends.
So if you need a variable outside a block, declare it in the outer block.
Scope and lifetime work together: scope answers "where can you see it", lifetime answers "how long does it live".
Exercise Define bonus in a block and add it to total
Assign 0 to int total. Inside a block, assign 10 to int bonus. Update total with total = total + bonus;. Outside the block, print total with Console.WriteLine.
Show example solution
Start with int total = 0;, then add the block { int bonus = 10; total = total + bonus; } and finally Console.WriteLine(total);.
Example solution:
int total = 0;
{
int bonus = 10;
total = total + bonus;
}
Console.WriteLine(total);
Test yourself
-
Assign 5 to count inside the block
int count = 0;
{
count = ____;
}
Console.WriteLine(count);
Show answer
int count = 0;
{
count = 5;
}
Console.WriteLine(count);
-
What is the output of the following code?
int x = 5;
{
int y = 10;
x = x + y;
}
Console.WriteLine(x);
Show answer
15 — Correct! x is declared in the outer block; x = x + y makes it 15, printed outside.
-
Match each concept to its meaning
- scope
- visibility region
- block
- between curly braces
- local variable
- declared in a method
- lifetime
- how long it lives
Next lesson: Summary - Variables