Scope is the hierarchical context bound by a code block or language construct. C# prevents two declarations with the same name declared in the same scope. For example, it is not possible to define two local variables in the same code block with the same name; the code block bounds the scope. Similarly, it is not possible to define two methods called Main() within the same class.
Scope is hierarchical because it is not possible to define a local variable directly within a method and then to define a new variable with the same name inside an if block of the same method. The scope of the initial variable declaration spans the scope of all code blocks defined within the method. However, a variable declared within the if block will not be in the same scope as a variable defined within the else block. Furthermore, the same local variable name can be used within another method because the method bounds the scope of the local variable.
Scope restricts accessibility. A local variable, for example, is not accessible outside its defining method. Similarly, code that defines a variable in an if block makes the variable inaccessible outside the if block, even while still in the same method. In Listing 3.27, defining a message inside the if statement restricts its scope to the statement only. To avoid the error, you must declare the string outside the if statement.
Listing 3.27. Variables Inaccessable Outside Their Scope
Output 3.15 shows the results of Listing 3.27.