Where a Variable Lives: Scope and Code Blocks

A variable can be used only inside the block where it's declared, so you'll learn to declare each one where the code that needs it can see it, and how blocks, methods, classes and namespaces nest.

Novice · C# · Updated

By

After this lesson you can

  • Declare a variable inside or outside a code block so the code that uses it can see it
  • Write an if without braces when its body is one line, and spot a line that only looks like part of the if
  • Explain the scope of a method's variables and how namespaces, classes and methods nest, with using to shorten a name

Key takeaways

  • A code block is the lines between a pair of curly braces. A variable declared inside a block can be used only from its declaration to that block's closing brace.
  • Code inside a block can see the variables declared outside it, but not the other way round. To use a value after a block, declare its variable before the block.
  • An if whose body is one line can leave out the braces, but only that one line belongs to the if, however the next lines are indented.
  • A method's parameters and the variables declared in its body live only inside that method. Namespaces hold classes, classes hold methods, and methods hold blocks.
  • Declare each variable in the smallest block that works, as close as you can to where it's used.

You've written a few methods now, and sooner or later you'll write a line like Console.WriteLine(result); and get an error that seems to make no sense: The name 'result' does not exist in the current context. The variable is right there, a few lines up. Every C# programmer meets this error in their first week, and it isn't a typo. It's C# telling you where your variable lives.

The error: a variable that can't be seen

The football program should print Win when your team scores more. Here's a first try. It uses if, which you met in the last lesson: the lines in its curly braces run only when the condition in its parentheses is true.

int ourScore = 21;
int theirScore = 14;

if (ourScore > theirScore)
{
    string result = "Win";
}

Console.WriteLine(result);

It doesn't build. The compiler says:

error CS0103: The name 'result' does not exist in the current context

result was declared, but inside the if's curly braces, and the last line is outside them. By the time the program reaches that line, result is gone.

Code blocks and scope

Think of the rooms in a house. Something you leave in the kitchen is there while you're in the kitchen; from the garage, you can't reach it. Code works the same way:

  • A code block is the lines between a pair of curly braces, { and }: the body of an if, the body of a method.
  • A variable's scope is the part of the program where its name can be used. A variable declared inside a block is in scope from its declaration to that block's closing brace, and nowhere else.
  • A variable declared inside a block, or a method, is called a local variable: it's local to that block.

Blocks sit inside other blocks, like a pantry inside the kitchen. The rule has two halves:

  • Inside can see out. Code in a block can use the variables declared outside it, earlier in the enclosing code.
  • Outside can't see in. Code outside a block can't use the variables declared inside it.

Nested rooms drawn as boxes inside boxes: the largest box is the namespace Football, inside it the class Scoreboard, inside that the method FinalScore, and inside that the variable total. An arrow from the innermost box out to the outer ones is marked with a check, "inside can see out", and an arrow from outside into the innermost box is marked with a cross, "outside can't see in"

Declare it outside to use it after

To use result after the if, declare it before the block, outside it. Inside the block, give it a new value; after the block, it's still there:

int ourScore = 21;
int theirScore = 14;
string result = "Loss";

if (ourScore > theirScore)
{
    result = "Win";
}

Console.WriteLine(result);
Win

The if changes result (inside can see out), and the last line prints it, because result belongs to the whole program, not to the block. Notice the inside line has no string in front: it gives the existing variable a new value. Writing string result = "Win"; there would try to declare a second variable with the same name, and C# doesn't allow a block to reuse a name that's already in scope around it.

One-line ifs without braces

When an if runs exactly one line, you may leave out the braces:

int ourScore = 21;
int theirScore = 14;

if (ourScore > theirScore)
    Console.WriteLine("Win");

Console.WriteLine("Final: " + ourScore + " to " + theirScore);
Win
Final: 21 to 14

Without braces, the if owns only the next line. Indenting a second line doesn't make it part of the if. Here the home team lost, and the program still rings the bell:

int ourScore = 10;
int theirScore = 14;

if (ourScore > theirScore)
    Console.WriteLine("Win");
    Console.WriteLine("Ring the victory bell!");

Console.WriteLine("Final: " + ourScore + " to " + theirScore);
Ring the victory bell!
Final: 10 to 14

C# ignores indentation. Only Console.WriteLine("Win"); belongs to the if; the bell line runs every time. When the body is more than one line, it needs braces. Many teams use braces even for one line, so a line added later can't fall outside by accident.

A method's variables stay in the method

A method's body is a block too. Its parameters and the variables declared in its body are local to the method: they exist while the method runs, and code outside it can't use them.

int seasonWins = 8;

ShowRecord(2);

void ShowRecord(int losses)
{
    int gamesPlayed = seasonWins + losses;
    Console.WriteLine(seasonWins + " wins in " + gamesPlayed + " games");
}
8 wins in 10 games
  • losses and gamesPlayed live only inside ShowRecord. A line at the top of the file that used gamesPlayed wouldn't build.
  • ShowRecord can read seasonWins, because in a program written as top-level statements, the methods at the bottom are inside the program's block, and inside can see out.
  • A method in a class, such as Scoreboard.FinalScore from Organizing Code into Methods, can't see the program's top-level variables at all. That's one reason to hand a method what it needs as parameters: then it works wherever it lives.

Each call gets its own fresh set of local variables, too. Calling ShowRecord twice makes two separate gamesPlayed variables, one after the other.

Namespaces, classes and methods: rooms inside rooms

Scope goes up as well as down. Your blocks live in methods, methods live in classes, and classes live in namespaces. A namespace is a named group of classes, like the city in a street address: two towns can both have a Main Street, and the city name tells them apart. Two libraries can both have a class called Scoreboard, and their namespaces keep them apart.

Level Holds Example
Namespace Classes Football
Class Methods (and, later, data) Scoreboard
Method Blocks and local variables FinalScore
Block Local variables the body of an if

Here's the scoreboard from Organizing Code into Methods, now inside a namespace of its own:

using Football;

Console.WriteLine(Scoreboard.FinalScore(12, 14, 6, 7));

namespace Football
{
    static class Scoreboard
    {
        public static int FinalScore(int q1, int q2, int q3, int q4)
        {
            int total = q1 + q2 + q3 + q4;
            return total;
        }
    }
}
39

A class's full name includes its namespace: Football.Scoreboard. The first line, using Football;, is a using directive: it tells C# "look in the Football namespace too", so the program can write Scoreboard instead of Football.Scoreboard. Without it, the call would have to be Football.Scoreboard.FinalScore(12, 14, 6, 7).

You've been relying on this since your first program. Console lives in the System namespace, so its full name is System.Console. Both lines here print the same thing:

System.Console.WriteLine("Kickoff at 7:00");
Console.WriteLine("Kickoff at 7:00");
Kickoff at 7:00
Kickoff at 7:00

The short one works because a new C# project adds using System; and a few other common namespaces for you. The exercises' files start with namespace MethodsExercise;: that one-line form puts everything in the file into the namespace MethodsExercise, without an extra pair of braces.

Choose the smallest scope that works

Where should a variable live? In the smallest block that works, declared as close as you can to where it's used:

DisplayTeamScores("Georgia", 12, 14, 6, 7);
DisplayTeamScores("Alabama", 14, 17, 10, 14);

void DisplayTeamScores(string teamName, int q1, int q2, int q3, int q4)
{
    int finalScore = q1 + q2 + q3 + q4;
    Console.WriteLine(teamName + ": " + finalScore);
}
Georgia: 39
Alabama: 55

finalScore is needed only inside DisplayTeamScores, so it's declared there. Nothing else in the program can change it by mistake, and a reader looking for where it gets its value finds it on the line above where it's used. If it were declared at the top of the program instead, every method could change it, and a bug in one method could show up in another. Declare a variable outside a block only when the code after the block needs it, as result did. Three questions settle it:

  1. Used only inside the block? Declare it inside the block.
  2. Needed after the block? Declare it before the block.
  3. Needed only in one method? Declare it in that method.

Do it: let the game's result out of its block

The scoreboard needs a method that says whether your team won. Someone started GameResult, but it always returns an empty string: each branch declares its own result inside its block, and the return line after the blocks can't see any of them.

The method gets two values:

  • ourScore: the points your team scored, an int (21).
  • theirScore: the points the other team scored, an int (14).

College football games can't end in a tie (they go to overtime), so there are two answers. For example:

Our score Their score Result
21 14 "Win"

So GameResult(21, 14) returns "Win". (The starter's else block runs when the if's condition is false, as in the If lesson.)

Your job: fix GameResult(int ourScore, int theirScore) so it returns the result as a string.

  • When ourScore is higher than theirScore, return "Win".
  • Otherwise, return "Loss".
  • Keep the if and else; change where result is declared so the return line can use it.

Practiced live on the lesson page: write the C# right there and check it.

Check yourself

2 questions to try on the lesson page.

So what

Every variable lives in a block, and only the code in that block can use it. Declare a variable where the code that needs it can see it, and no wider: most "does not exist in the current context" errors are fixed by moving one declaration up a level.

Key terms