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,
In the above example, we have created a variable named str inside f1().
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,
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,
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);
}
}
// Inside f1()
string str = "method level";
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();
}
}
//error
Console.WriteLine(i);
Error CS0103 The name 'i' does not exist in the current context