Algorithm


In C#, the scope of a variable refers to the region of the code where the variable can be accessed or modified. C# has various levels of variable scope, and understanding them is crucial for writing maintainable and bug-free code. Here are the main types of variable scope in C#:

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

Class Level Scope
Method Level Scope
Block Level Scope

 

Code Examples

#1 C# Progrram Class Level Variable Scope

Code - C# Programming

using System;
namespace VariableScope {
  class Program {

    // class level variable
    string str = "Class Level";

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

    static void Main(string[] args) {
      Program ps = new Program();
      ps.display();

      Console.ReadLine();
    }
  }
}
Copy The Code & Try With Live Editor

Output

x
+
cmd
Class Level

#2 Method Level Variable Scope in C# Program

Code - C# Programming

using System;

namespace VariableScope {
  class Program {

    public void method1() {
      // display variable inside method
      string str = "method level";
    }

    public void method2() {

      // accessing str from method2()
      Console.WriteLine(str);
    }

    static void Main(string[] args) {
      Program ps = new Program();
      ps.method2();

      Console.ReadLine();
    }
  }
}
Copy The Code & Try With Live Editor

#3 Method Level Variable Scope in C# Program

Code - C# Programming

using System;
namespace VariableScope {
  class Program {

    public void display() {
     string str = "inside method";

      // accessing method level variable
      Console.WriteLine(str);
    }

    static void Main(string[] args) {
    Program ps = new Program();
    ps.display();

    Console.ReadLine();
    }
  }
}
Copy The Code & Try With Live Editor

Output

x
+
cmd
inside method

#4 Block Level Variable Scope in C# Programming

Code - C# Programming

using System;

namespace VariableScope {
  class Program {
    public void display() {

      for(int i=0;i < =3;i++) {
        	 
      }
    Console.WriteLine(i);
    }

    static void Main(string[] args) {
      Program ps = new Program();
      ps.display();

      Console.ReadLine();
    }
  }
}
Copy The Code & Try With Live Editor
Advertisements

Demonstration


C# Programming Variable Scope