C# Variable Scope

A variable scope refers to the availability of variables in certain parts of the code.

In C#, a variable has three types of scope:

  • Class Level Scope

  • Method Level Scope

  • Block Level Scope

C# Class Level Scope

In C#, when we declare a variable inside a class, the variable can be accessed within the class. This is known as class level variable scope.

Class level variables are known as fields and they are declared outside of methods, constructors, and blocks of the class. For example,

using System;
class Program
{
    static void Main(string[] args)
    {
        A obj = new A();
        obj.f1();
        obj.f2();
        Console.ReadLine();
    }
}

class A
{
    String str = "Class Level";

    public void f1()
    {
        Console.WriteLine(str);
    }

    public void f2()
    {
        Console.WriteLine(str);
    }
}

In the above example, we have initialized a variable named str inside the A class.

Since it is a class level variable, we can access it from any method present inside the class.

This is because the class level variable is accessible throughout the class.

Method Level Scope

When we declare a variable inside a method, the variable cannot be accessed outside of the method. This is known as method level variable scope. For example,

using System;
class Program
{
    static void Main(string[] args)
    {
        A obj = new A();
        obj.f1();
        obj.f2();
        Console.ReadLine();
    }
}

class A
{
   
    public void f1()
    {
        String str = "method Level";
        Console.WriteLine(str);
    }

    public void f2()
    {
        //error
        //Console.WriteLine(str);
    }
}

In the above example, we have created a variable named str inside f1().

// Inside f1()
string str = "method level";

Here, str is a method level variable. So, it cannot be accessed outside f1().

However, we cannot access the str variable from the f2(), it's a compile time error.

Block Level Scope

When we declare a variable inside a block (for loop, while loop, if/else), the variable can only be accessed within the block. This is known as block level variable scope. For example,

using System;
class Program
{
    static void Main(string[] args)
    {
        for (int i = 0; i < 5; i++)
        {
            Console.WriteLine(i);
        }

        //error
        Console.WriteLine(i);

        Console.ReadLine();
    }
}

In the above program, we have initialized a block level variable i inside the for loop.

Since i is a block level variable, when we try to access the variable outside the for loop,

//error
Console.WriteLine(i);

we get an error.

Error	 CS0103  The name 'i' does not exist in the current context

Last updated