C# Variable Scope

In C#, the scope of a variable defines its visibility and lifetime.

The scope of a variable is usually determined by the curly braces{}that define a code block.

The following are some basic rules about C# variable scope:

Local variables

Variables declared within code blocks such as methods, loops, and conditional statements are local variables; they are only visible within the code block in which they are declared.

Example

void MyMethod()
{
    int localVar = 10; // local variable
    // ...
}
// localVar is not visible here

Block-level scope

In C# 7 and later, block-level scope was introduced, meaning that any block created using curly braces{}can define the scope of a variable.

Example

{
    int blockVar = 20; // Block scope
    // ...
}
// blockVar is not visible here

Method parameter scope

Method parameters also have their own scope; they are visible throughout the entire method.

Example

void MyMethod(int parameter)
{
    // parameter is visible throughout the method
    // ...
}

Global variables

Variables defined at the class member level are member variables; they are 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 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 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 is visible within the loop body
}
// i is not visible here

Overall, variable scope helps manage the visibility and lifetime of variables, ensuring that variables are used within their valid scope, and also helps prevent naming conflicts.

other extensions