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,
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,
we get an error.
Last updated