NGWS SDK Documentation  

This is preliminary documentation and subject to change.
To comment on this topic, please send us email at ngwssdk@microsoft.com. Thanks!

3.5 Scopes

The scope of a name is the region of program text within which it is possible to refer to the entity declared by the name without qualification of the name. Scopes can be nested, and an inner scope may redeclare the meaning of a name from an outer scope. The name from the outer scope is then said to be hidden in the region of program text covered by the inner scope, and access to the outer name is only possible by qualifying the name.

Within the scope of a namespace, class, struct, or enumeration member it is possible to refer to the member in a textual position that precedes the declaration of the member. For example

class A
{
   void F() {
      i = 1;
   }
   int i = 0;
}

Here, it is valid for F to refer to i before it is declared.

Within the scope of a local variable, it is an error to refer to the local variable in a textual position that precedes the variable-declarator of the local variable. For example

class A
{
   int i = 0;
   void F() {
      i = 1;               // Error, use precedes declaration
      int i;
      i = 2;
   }
   void G() {
      int j = (j = 1);      // Legal
   }
   void H() {
      int a = 1, b = ++a;   // Legal
   }
}

In the F method above, the first assignment to i specifically does not refer to the field declared in the outer scope. Rather, it refers to the local variable and it is in error because it textually precedes the declaration of the variable. In the G method, the use of j in the initializer for the declaration of j is legal because the use does not precede the variable-declarator. In the H method, a subsequent variable-declarator legally refers to a local variable declared in an earlier variable-declarator within the same local-variable-declaration.

The scoping rules for local variables are designed to guarantee that the meaning of a name used in an expression context is always the same within a block. If the scope of a local variable was to extend only from its declaration to the end of the block, then in the example above, the first assignment would assign to the instance variable and the second assignment would assign to the local variable, possibly leading to errors if the statements of the block were later to be rearranged.

The meaning of a name within a block may differ based on the context in which the name is used. In the example

class Test
{
   static void Main() {
      string A = "hello, world";
      string s = A;                        // expression context
      Type t = typeof(A);                  // type context
      Console.WriteLine(s);               // writes "hello, world"
      Console.WriteLine(t.ToString());      // writes "Type: A"
   }
}

the name A is used in an expression context to refer to the local variable A and in a type context to refer to the class A.