When a variable is declared in a method of a C# program, its scope is pre-defined and its visibility is defined for the rest of the program. When it's created this way, the variable will be available as long as its method is in execution. However, when the control is passed to another method, its scope ends. This type of variable is called a local variable.
In this guide, we will learn about the scope of local variables and combat the issues related to the position of variable declaration in C# code.
An example of a local variable:
1using System;
2public class NewProgram {
3 public static void Main(string[] args) {
4 int x;
5 x = 10; // local variable
6 Console.WriteLine("Value:" + x);
7 }
8}
Output will be:
1Value:10
These variables can be used only within code blocks that are inside that function.
There are other ways to define and use a variable by declaring it in a class (or as a global variable), which allows it to be available to all methods in that class.
Global variables can be accessed from anywhere in a class or namespace. C# does not directly support global variables, but the functionality of global variables can be achieved by creating a static class, which is helpful in specific cases. As a general practice, it's best to avoid using global variables because they violate the object-oriented programming philosophy of C# and can make things complicated while multi-threading, etc. Be cautious to avoid conflicts by adding locks or ensuring that only one thread has access to the global variable at any given instance.
The scope of a variable is within the full code block of its declaration. Also, since the code blocks are sometimes nested as per the application requirement, a loop defined within the method of a class gives three nested code blocks and subsequently three levels of nested-scope. If a variable is defined in any of these scopes, it will be visible to the current scope and the ones that are nested within it.
In simple terms:
To understand the scope of a local variable well, it is important to understand the levels of scope in C# .
Variables defined in the class are available to all non-static methods declared in the class, called fields or class members. Their access modifier does not affect their scope within the class, and they can be accessed outside of the class using access modifiers.
For example:
1using System;
2class ClassScope { // class level scope starts here
3 int abc = 1000; // class level variable with class level scope
4 public void display() {
5 Console.WriteLine(a); // method to access the class level variable
6 } // method ends here
7} // class level scope ends
Variables declared within a method are available to its corresponding parts and also the nested code blocks. They are not available outside the method. These are local variables. Variables cease to exist after method execution is complete.
1static void Main(string[] args) {
2 int marks; // Declared at the method-level
3 marks = 100; // Used at the method-level
4 if (marks >= 50)
5 Console.WriteLine("Great Marks are : {0}", marks); // Used in the nested scope
6 else
7 Console.WriteLine("Bad marks are : {0}", marks); // Again, used in the nested scope
8}
Output will be:
1Great Marks are : 100
We have explained earlier that variables declared in a nested scope will not be available outside their respective code blocks. These can be called loop variables. We will show in the following example that a variable declared in a nested scope of an if
statement cannot be used at the method level and will not compile.
1static void Main(string [] args){
2 int score = 100;
3 if (score >= 60)
4 string message = "Good score"; // Declared in if statement
5 else
6 string message = "Poor score"; // Declared in else statement
7 Console.WriteLine(message); // Variable unavailable
8}
Output will be:
1Error(s):
2(15:9) Embedded statement cannot be a declaration or labeled statement
3(17:6) Embedded statement cannot be a declaration or labeled statement
If we wanted to make this code work, we could declare the variable before the if
statement and assign a value to it within the if
statement.
*Note: There is a crucial difference in between the scope definition in C and C#.
If a C# variable is defined within the local scope in a block (if/else) which is conflicting with a variable defined outside following that block, it will give an error. A similar code is compiled under C/C++ or Java. Local variables will remain in scope throughout the entire block where they have been declared. This is the opposite of C++, where the local variables are in scope at points in their block only after they have been declared.
1public void function(){
2 if (true) {
3 /* scope of local if */
4 int a = 2;
5 System.Console.WriteLine(a);
6 } else {
7 /* no conflict arises with same if/else */
8 int a = 4;
9 System.Console.WriteLine(a);
10 }
11
12 if (true) {
13 /* no conflict with local from different if scope */
14 int a = 10;
15 System.Console.WriteLine(a);
16 }
17}
We know that while declaring a scope, any local variable from the outer scope is known. There is no possibility that a local variable within a scope would override the local variable from an outside scope.
This guide has explained the scope of local variables in C#. Armed with this knowledge, we can avoid common binding issues and errors and define variables in the correct scope. If an unknown error or garbage value occurs within variables, it can be resolved by assigning values once the scope is well known.
Happy learning C#!