C# Tutorial - Scope

posted Jun 28, 2011, 7:12 PM by magic stone

When using variable within a control structure, the variable only has scope with the curly brackets that it is declared between. Once the structure has finished, the variable goes out of scope and cannot be used anymore.

Examples of this are a do…while loop:

int i = 0;
do
{
  // j only has scope within the loop
  int j = 2;
  Console.WriteLine( “j = ” + j);
  i++;
}
While( i < 10 )
// j is no longer in scope

or a for loop:

for( int i = 0; i < 10; i++ )
{
  // j only has scope within the loop
  int j = 2;
  Console.WriteLine( “j = ” + j);
}
// j is no longer in scope

Defining Class Scope

class ScopeExmaple
{
  private void methodA()
  {
    _a = 2;
  }

  private void methodB()
  {
    _a = 3;
  }

  private int _a = 0;
}

A variable with class scope does not have to be declared before any method that uses it. The compiler sorts this out at compile time.

Defining Local Scope

private void methodA()
{
  int _a = 0;

  for( int i = 0; i < 10; i++ )
  {
    _a = 2;
    Console.WriteLine( “a = ” + _a);
    _a = _a + 2;
  }
}

In the above example, the local variable is declared before it is used. However, if we were to declare the variable after it is used as in class scope, then a compile time error will occur. This is shown in the next example.

private void methodA()
{
  for( int i = 0; i < 10; i++ )
  {
    // The compile time error will occur here as the variable has
    // not been declared yet.
    _a = 2;
    Console.WriteLine( “a = ” + _a);
    _a = _a + 2;
  }

  int _a = 0;
}

Comments