Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

C# Variable Scope

C# Variable Scope

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

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

Here are some basic rules about variable scope in C#:

local variables

Variables declared inside a block of code such as a method, loop, or conditional statement are local variables; they are visible only within the 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 with curly braces {} can define the scope of a variable.

Example

{

   

int

blockVar

=

20

;

// Block-level scope

   

// ...

}

// blockVar is not visible here

Method parameter scope

The parameters of a method also have their own scope; they are visible throughout the method.

Example

void

MyMethod

(

int

parameter

)

{

   

// parameter is visible throughout the method

   

// ...

}

Global Variables

Variables defined at the member level of a class are member variables; they are visible throughout the class. If defined at the namespace level, they are visible throughout the 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

A loop variable declared in a for loop is 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 they are used within their valid range and helping to prevent naming conflicts.