←to practical programming

Note "scope"

The scope of a variable is the part of the program where the variable is accessible.

C# is lexically scoped: the scope of a variable in a C#-program can be determined at compile time (that is, lexically — by reading the source code) and is independent of the state of the runtime-system.

Scope-wise the variables in C# can be divided into three classes:

  1. Class level variables (class-scope)
  2. Method level variables (method-scope)
  3. Block level variables (block-scope)

Variables declared in the class-scope (these variables are called fields or members) can be accessed anywhere inside the class and, if decleared public, can also be accessed outside of the class.

Variables declared inside a method are accessible anywhere inside the method but are not accessible outside of the method. Method-scope variables can shadow (that is, replace, if they have the same name) class-scope variables. Method-scope variables are deleted when the method exits.

Variables declared inside a block are block-scope variables. They are not visible outside of their block. Block-scope variables are not allowed to shadow class- and method-scope variables (a rather unfortunate feature of csharp, in my opinion). Block-scope variables are deleted when the block exits.