-- Learn not just technology, but also dreams!
- Home
- HTML
- JavaScript
- CSS
- Vue
- React
- Python3
- Java
- C
- C++
- C#
- AI
- Go
- SQL
- Linux
- VS Code
- Bootstrap
- Git
- Local Bookmarks
C# Tutorial
C# Advanced Tutorials
C# Variable Scope
In C#, the scope of a variable defines its visibility and lifetime.
The scope of a variable is typically determined by the code block defined by curly braces {}.
Here are some basic rules regarding C# variable scope:
Local Variables
Variables declared inside code blocks such as methods, loops, and conditional statements are local variables. They are only visible within the code block where they are declared.
Example
void MyMethod()
{
int localVar =10;// Local variable
// ...
}
// localVar Not visible here
Block-Level Scope
In C# 7 and later, block-level scope was introduced, meaning any block created with curly braces {} can define the scope of a variable.
Example
{
int blockVar =20;// Block scope
// ...
}
// blockVar Not visible here
Method Parameter Scope
Method parameters have their own scope and are visible throughout the entire method.
Example
void MyMethod(int parameter)
{
// parameter Visible throughout the entire method
// ...
}
Global Variables
Variables defined at the class member level are member variables, visible throughout the entire class. If defined at the namespace level, they are visible throughout the entire namespace.
Example
class MyClass
{
int memberVar =30;// Member variable, visible throughout the entire class
}
Static Variable Scope
Static variables are declared at the class level, but their scope is also limited to the class in which they are defined.
Example
class MyClass
{
static int staticVar =40;// Static variable, visible throughout the entire class
}
Loop Variable Scope
Loop variables declared in a for loop are visible within the loop body.
Example
for(int i =0; i <5; i++)
{
// i Visible within the loop body
}
// i Not visible here
Overall, variable scope helps manage the visibility and lifetime of variables, ensuring they are used within their valid range, and also helps prevent naming conflicts.
YouTip