Scope of the Variable in C#

The scope of a variable is simply the region of the program in which that variable is usable. Scope applies to methods as well as variables. The scope of an identifier (of a variable or method) is linked to the location of the declaration that introduces the identifier into the program.
 
Local Scope
 
The opening and closing curly braces that forms the body of a method define a scope. Any variables you declare inside the body of a method are scoped to that method; they disappear when the method ends and can be accessed only by code running within that method.
 
These variables are called local variables because they are local to the method in which they are declared; they are not in scope in any other method. This arrangement means that you can’t use local variables to share information between methods.
 
Example:
 
class scope
{
void firstMethod()
{
int abc;
…
}

void secondMethod()
{
abc=15;  //error- variable not in scope
…
}
}
 
The above code can’t compile. It shows compile time error because secondMethod is trying to use the variable abc which is not in scope. The variable abc is available only to statements in firstMethod.
 
Class Scope
 
The opening and closing curly braces that forms the body of a method define a scope. Any variables you declare inside the body of a class (but not inside the method) are scoped to that class. The proper C# name for the variables defined by a class is fields. You can use these fields to share information between methods.
 
Example:
 
class scope
{
void firstMethod()
{
abc=15;
…
}

void secondMethod()
{
abc=15;
…
}

int abc=0;
}
 
The variable abc is defined within the class scope but outside the firstMethod and secondMethod. So, variable abc has in the scope of the class and is available for use by all methods in the class.
 
Note: There is one point to notice in the above example. In a method, you must declare a variable before you can use it. Fields are a little different. A method can use a field before the statement that defines the field- the compiler short out the details for you.
Scroll to Top