Scope
A name's scope is the region of code where you can use it.
In C#, scope is set by the enclosing block, which is a pair of curly braces { }.
Why this matters
Scope keeps names from overwriting each other. A variable declared inside one method can't be seen or changed by another method.
This lets you reuse common names like i, count, or result without side effects.
static void Add(int num)
{
int step = 1; // local: exists ONLY inside Add
num += step;
}
static void Print()
{
int total = 0;
Console.WriteLine(total); // ✅ OK
Console.WriteLine(step); // ❌ Error: 'step' does not exist in the current context
}
The Rules
1. A local is scoped to its block
A variable declared in a block is usable from its declaration to the closing }.
2. Child blocks can see parent locals
Nested blocks, such as if and loops can use variables from the blocks that contain them.
3. Parent blocks can't see child locals
Once the block closes, the name is GONE.
4. Parameters are locals of the function
You can't use them outside that function.
5. Members are scoped to their type
Fields, constants, and methods are visible throughout their class, and their access modifiers (private, public, and so on) control access from outside the class.
{
string message = "Hello";
if (message.Length > 0)
{
Console.WriteLine(message); // ✅ OK: the child block sees the parent's local
string extra = "!";
}
Console.WriteLine(extra); // ❌ Error: extra's scope ended at the }
}
C# doesn't let a nested local reuse a name from an enclosing local scope:
int total = 0;
for (int i = 0; i < 3; i++)
{
int total = i; // ❌ Error: 'total' is already declared in the scope
}
Constants
Use const for values that never change.
These are always declared at the top of the file so every function below can use them:
const int Min = 1;
const int Max = 6;
static int Roll()
{
// the upper bound is exclusive
return Random.Shared.Next(Min, Max + 1);
}
Console.WriteLine(Roll());