DEV Community

Sabin Sim
Sabin Sim

Posted on

07. C# (Scope & Code Blocks)

0) Goal of This Lesson

Understanding where a variable is visible,
and why it suddenly becomes inaccessible.

If you miss this concept:

  • if / else will feel inconsistent
  • variables will “randomly” stop working
  • method parameters won’t make sense later

Scope is not syntax trivia.
It defines what code is allowed to see what data.


1) The Simplest Rule of Scope

A variable is only visible inside the code block where it is declared,
and any nested blocks inside it.

A code block is anything wrapped in { }.

{
    // this is one scope
}
Enter fullscreen mode Exit fullscreen mode

When execution leaves this block,
variables declared inside it no longer exist.


2) Variable Declared in the Outer Scope (Works Everywhere Inside)

Run this code:

using System;

class Program
{
    static void Main()
    {
        string userChoice = Console.ReadLine();

        if (userChoice == "A")
        {
            Console.WriteLine("IF block");
        }
        else
        {
            Console.WriteLine("ELSE block");
        }

        Console.WriteLine(userChoice);
    }
}
Enter fullscreen mode Exit fullscreen mode

Observation

  • userChoice is accessible:

    • inside if
    • inside else
    • after the if / else

Rule

A variable declared in an outer block
is visible in all inner blocks.


3) Variable Declared Inside an if Block

Now run this:

using System;

class Program
{
    static void Main()
    {
        string userChoice = "A";

        if (userChoice == "A")
        {
            int number = 10;
            Console.WriteLine(number);
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

Observation

  • Code compiles
  • number prints correctly

So far, everything looks fine.


4) Why the Same Variable Fails Outside the Block

Now add one line:

Console.WriteLine(number);
Enter fullscreen mode Exit fullscreen mode

Full code:

if (userChoice == "A")
{
    int number = 10;
}

Console.WriteLine(number); // compile-time error
Enter fullscreen mode Exit fullscreen mode

Observation

  • Code does not compile
  • Error: The name 'number' does not exist in the current context

Rule

A variable declared inside a block
stops existing when the block ends.

This is checked before execution, by the compiler.


5) if and else Are Separate Scopes

Run this example:

using System;

class Program
{
    static void Main()
    {
        string userChoice = "A";

        if (userChoice == "A")
        {
            int number = 10;
            Console.WriteLine(number);
        }
        else
        {
            Console.WriteLine(number); // compile-time error
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

Observation

  • number exists only in the if block
  • else cannot see it

Rule

if and else blocks are sibling scopes, not shared scopes.

Declaring a variable in one does not make it visible in the other.


6) Nested Blocks Can See Outer Variables

Run this:

using System;

class Program
{
    static void Main()
    {
        string userChoice = "A";

        if (userChoice == "A")
        {
            int number = 10;

            if (number > 5)
            {
                Console.WriteLine(number);
                Console.WriteLine(userChoice);
            }
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

Observation

  • Inner if can access:

    • number
    • userChoice

Rule

Inner blocks can see variables from outer blocks.
Outer blocks cannot see variables from inner blocks.


7) Same Variable Name Rules

7.1 Same scope — NOT allowed

if (true)
{
    int x = 10;
    int x = 20; // compile-time error
}
Enter fullscreen mode Exit fullscreen mode

Rule:

A variable name must be unique within the same scope.


7.2 Different scopes — allowed

if (true)
{
    int x = 10;
}
else
{
    int x = 20;
}
Enter fullscreen mode Exit fullscreen mode

Rule:

Different blocks create different scopes,
even if they are part of the same if / else structure.


8) How to Verify Scope Using Debugging

  1. Place a breakpoint inside the block where the variable is declared
  2. Start debugging
  3. Observe the variable in the debugger
  4. Step out of the block

Observation

  • The variable disappears from the debugger
  • This confirms the scope boundary

9) The Mental Check That Solves 90% of Scope Confusion

Whenever something “suddenly doesn’t work”, ask:

Was this variable declared inside the braces
where I am currently standing?

If the answer is no,
the compiler is doing exactly what it should.


10) One-Line Summary

Scope is defined by { }.
Variables exist only inside the block where they are declared,
and disappear when that block ends.

Top comments (0)