C#: Variable scope

This entry is part 25 of 71 in the series C#

You can declare variables in several different places:

  • In a class body as class fields. Variables declared here are referred to as class-level variables.
  • As parameters of a method or constructor.
  • In a method’s body or a constructor’s body.
  • Within a statement block, such as inside a while or for block.

Variable scope refers to the accessibility of a variable. The rule is that variables defined in a block are only accessible from within the block. The scope of the variable is the block in which it is defined.

For example, consider the following for statement:

for (int x = 0; x < 5; x++)

The variable x is declared within the for statement. As a result, x is only available from within this for block. It is not accessible or visible from anywhere else.

The next post talks about variables in a nested block.

Series Navigation<< C#: Static classes
C#: Variable scope in nested block >>