C# Scope
Variable Scope
In C#, a variable can only be used in the part of the program where it is created. This part is called the variable's scope.
Scope keeps variables apart. A variable in one method cannot be changed by another method by mistake, and different methods can use the same variable names.
Method Scope
A variable that is declared inside a method only exists inside that method. Other methods cannot use it:
Example
static void ShowScore()
{
int score = 50;
Console.WriteLine(score);
}
static void Main(string[] args)
{
ShowScore();
Console.WriteLine(score); // Error
}
The compiler shows an error like this:
prog.cs(16,25): error CS0103: The name `score' does not exist in the current context
The variable score belongs to ShowScore(). Main() cannot see it, so C# says that the name does not exist.
To get a value out of a method, use a return value.
Because each method has its own variables, different methods can use the same variable name. They are two different variables, and they do not affect each other:
Example
static void PlayerOne()
{
int score = 10;
Console.WriteLine("Player one: " + score);
}
static void PlayerTwo()
{
int score = 20;
Console.WriteLine("Player two: " + score);
}
static void Main(string[] args)
{
PlayerOne();
PlayerTwo();
}
Block Scope
A block is the code between curly braces { }, for example the code inside an if statement or a loop.
A variable that is declared inside a block can only be used inside that block:
Example
int points = 80;
if (points > 50)
{
string message = "You win!";
Console.WriteLine(message);
}
Console.WriteLine(message); // Error
The compiler shows an error like this:
prog.cs(17,25): error CS0103: The name `message' does not exist in the current context
To use the variable after the block, declare it before the block. Inside the block, you only change its value:
Example
int points = 80;
string message = "Try again";
if (points > 50)
{
message = "You win!";
}
Console.WriteLine(message);
The same is true for loops. In for (int i = 0; i < 5; i++), the variable i can only be used inside the loop.
Variables in the Class
A variable that is declared in the class, outside the methods, can be used by all methods in the class:
Example
class Program
{
static int score = 0;
static void AddPoints()
{
score = score + 10;
}
static void Main(string[] args)
{
AddPoints();
AddPoints();
Console.WriteLine(score); // 20
}
}
Both AddPoints() and Main() use the same score variable.
The variable needs the static keyword, just like the methods in Program. You will learn more about static in the Static chapter.