Scope of Variables
The scope of a variable defines where it can be accessed in the program. Depending on where the variable is declared, it can have class-level, local, or block scope. Understanding variable scope helps manage variable accessibility and avoid errors.
Key Concepts
- Class-Level Scope: Variables declared within a class but outside any methods are accessible throughout the class.
- Local Scope: Variables declared within a method are accessible only within that method.
- Block Scope: Variables declared inside a block (such as an
ifstatement or loop) are only accessible within that block.
Examples of Variable Scope
Class-Level Scope Example
class Program
{
// Class-level variable
static string message = "Class-level variable";
static void Main(string[] args)
{
// Access class-level variable
Console.WriteLine(message);
}
}
Output:
Explanation: The variable message is declared at the class level, meaning it can be accessed by any method within the class. In this case, it is accessed directly from the Main method.
Local Scope Example
class Program
{
static void Main(string[] args)
{
// Local variable
int number = 100;
Console.WriteLine($"Local variable value: {number}");
}
}
// This would cause an error
// Console.WriteLine(number); // Cannot access local variable outside method
Output:
Explanation: The variable number is declared within the Main method, meaning it is local to this method. Trying to access it outside the method would result in an error because its scope is limited to the method where it was declared.
Block Scope Example
class Program
{
static void Main(string[] args)
{
if (true)
{
// Block scope variable
string blockMessage = "Inside block scope";
Console.WriteLine(blockMessage);
}
// Uncommenting the next line will result in an error
// Console.WriteLine(blockMessage); // Block scope variable not accessible here
}
}
Output:
Explanation: The variable blockMessage is declared within the block of the if statement. This variable is only accessible inside the block where it was declared, and attempting to access it outside the block would result in an error.