Tutorialsteacher

Follow Us

Articles
  • C#
  • C# OOP
  • ASP.NET Core
  • ASP.NET MVC
  • LINQ
  • Inversion of Control (IoC)
  • Web API
  • JavaScript
  • TypeScript
  • jQuery
  • Angular 11
  • Node.js
  • D3.js
  • Sass
  • Python
  • Go lang
  • HTTPS (SSL)
  • Regex
  • SQL
  • SQL Server
  • PostgreSQL
  • MongoDB
Entity Framework Extensions - Boost EF Core 9
  Bulk Insert
  Bulk Delete
  Bulk Update
  Bulk Merge
  • All
  • C#
  • MVC
  • Web API
  • Azure
  • IIS
  • JavaScript
  • Angular
  • Node.js
  • Java
  • Python
  • SQL Server
  • SEO
  • Entrepreneur
  • Productivity

Scope of Variables in C#

In C#, the Scope of the variable determines the accessibility of the variable to a particular part of the application. Variables can be declared within the class, method, and code block of a loop, condition, etc.

There are three types of scopes in C#.

  • Class Level Scope
  • Method Level Scope
  • Code-Block Level Scope

Class Level Scope

A variable declared within a class is known as a field. It has a class-level scope that can be accessed anywhere in the class, such as class methods, properties, etc.

Example: Class Level Variables Scope
class Student
{
    private string _firstName = "Bruce"; 
    private string _lastName = "Lee";
    
    public void DisplayFullName()
    {
        Console.WriteLine(_firstName + " " + _lastName);
    }

    public string FullName
    {
        get
        {
            return _firstName + " " + _lastName; 
        }
    }
}
Try it

In the above example, the Student class contains two class variables (a.k.a. fields) _firstName and _lastName. These fields can be accessed anywhere within the class, i.e., within any non-static methods and properties.

The class level variables can also be accessed out of class using class objects depending on the access modifiers. The static variables of the class can only be accessed from the static methods or properties.

Method Level Scope

A variable declared within a method has a method level Scope. It is also known as a local variable of the method where it is declared. It cannot be accessed outside the method.

Any nested code blocks within the method can access this type of variable. It cannot be declared twice with the same name within the same scope.

The local variable's scope ends when the method execution completes, and they will be collected by the garbage collector.

The following example shows the method Level scope:

Example: Method Level Scope
class Program
{
    static string str = "Hello";

    static void Main(string[] args)
    {
        //Method level scope of variable declaration
        int a = 20;
        Console.WriteLine("a = {0}", a);

        //can access class level variables
        Console.WriteLine("str = {0}", str);
        
        Process();
        // Console.WriteLine("b = {0}", b); // can't access b
    }

    static void Process(){
        int b = 30;
        Console.WriteLine("b = {0}", b);

        //can access class level variables
        Console.WriteLine("str = {0}", str);
        
        // Console.WriteLine("a = {0}", a); // can't access a
    }
}
Try it

In the above example, the Main() method can only access variables declared in the Main() method but not variables of other methods. In the same way, the Process() method cannot access variables declared in the Main() or any other method.

Code-Block Level Scope

A variable declared within a loop or any block within brackets has the code-block level scope. A variable declared within a loop or code block cannot be accessed outside of it, whereas a variable declared outside of the loop can be accessible within the loop.

Example: Code-Block Scope
class Program
{
    static void Main(string[] args)
    {
        int count = 0;
       
        for (int i = 0; i < 5; i++)
            Console.WriteLine(i);
        
        //Console.WriteLine(i); //can't access i because it has loop level scope
        
        if (count == 0)
        {
            count++; //can access method variables

            int x = 10; //declared block level variable
        }
        
        //Console.WriteLine(x); //can't access block level variable
    }
}
Try it

In the above example, a variable i declared within a for loop. So, it can only be accessed within the for loop block and cannot be accessed outside for loop. In the same way, x is declared within the if block, so it can only be accessed in that block but not outside of it.

A variable must be declared outside of the code block to make it accessible to outside code.

TUTORIALSTEACHER.COM

TutorialsTeacher.com is your authoritative source for comprehensive technologies tutorials, tailored to guide you through mastering various web and other technologies through a step-by-step approach.

Our content helps you to learn technologies easily and quickly for learners of all levels. By accessing this platform, you acknowledge that you have reviewed and consented to abide by our Terms of Use and Privacy Policy, designed to safeguard your experience and privacy rights.

[email protected]

ABOUT USTERMS OF USEPRIVACY POLICY
copywrite-symbol

2024 TutorialsTeacher.com. (v 1.2) All Rights Reserved.