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

class Program {  static void Main(string[] args)  {     int playerCount;        Console.Write("Enter the number of players (1 or 2):");     if (playerCount != 1 || playerCount != 2)  {    string message =                                                                  "You entered an invalid number of players.";                          }  else  {            // ...  }  // Error:  message is not in scope.                                          Console.WriteLine(message);                                                  } }

Output 3.15 shows the results of Listing 3.27.

Output 3.15.

Microsoft (R) Visual C# 2005 Compiler version 8.00.50727.42 for Microsoft (R) Windows (R) 2005 Framework version 2.0.50727 Copyright (C) Microsoft Corporation 20012005. All rights reserved. <filename>: error CS0103: The name 'message' does not exist in the cur- rent context

Essential C# 2.0
Essential C# 2.0
ISBN: 0321150775
EAN: 2147483647
Year: 2007
Pages: 185 © 2008-2017.
If you may any questions please contact us: