๐ŸŽ“ A1Learner
๐Ÿ”

C# Scope

Scope is the part of a program where a name can be used. A variable keeps the scope of the block or method where it is declared.

Local inside a method

The variable count is declared inside Show. The print line sits in the same method and can use count.

using System;

class Program
{
    static void Show()
    {
        int count = 5;
        Console.WriteLine(count);
    }

    static void Main(string[] args)
    {
        Show();
    }
}

Same name, two methods

First and Second each declare a variable named value. Each method prints its own value.

using System;

class Program
{
    static void First()
    {
        int value = 10;
        Console.WriteLine(value);
    }

    static void Second()
    {
        int value = 20;
        Console.WriteLine(value);
    }

    static void Main(string[] args)
    {
        First();
        Second();
    }
}

Used outside its block

A bare block is a pair of braces with no condition or loop. The block prints secret, but the line after the block cannot use it.

using System;

class Program
{
    static void Main(string[] args)
    {
        {
            int secret = 42;
            Console.WriteLine(secret);
        }
        Console.WriteLine(secret);
    }
}

Example

using System;

class Program
{
    static void Main(string[] args)
    {
        int total = 5;
        {
            int bonus = 3;
            total = total + bonus;
            Console.WriteLine(total);
        }
        Console.WriteLine(total);
    }
}

Key points

  • A block is code inside a pair of curly braces.
  • A variable declared in a method can be used in that method.
  • A variable declared in a block can be used only in that block.
  • Two methods can use the same variable name.
  • Each method sees only its own variable with that name.

In this example, total is declared in Main before the inner block. The block adds bonus to total and prints 8. The last line sits after the block and prints total again. It also prints 8 because total belongs to Main.

Try it Yourself

Edit the code, then press Run.

Running is simulated ยท Programiz C# Compiler

Exercise

Where can a variable declared inside a block be used?