Member Scope





Member Scope

When we talk about scope, we talk about which parts of your code can reach a member or variable. You may recall the use of private variables declared in Listing 2.6. As we revealed earlier, the strings declared in this class can be used by any other member in the class. This variable is said to have class scope. Although this is handy for sharing data across the class, sometimes you don't need to declare a variable that is used by the entire class. In these cases we declare the variable in the body of the method.

In Listing 2.12, we show a variable declared in a method, and we show that it can't be reached by other methods. It is said to be out of scope when you attempt to get to it from another method. Specifically, the code will throw an "object reference not set to an instance of an object" error because TwoMethod() has no idea that MyString exists.

Demonstrating variable scope

C#

public class MyClass
{
  public string OneMethod()
  {
    string MyString = "hello";
    return MyString;
  }
  public string TwoMethod()
  {
    return MyString; // throws an exception
  }
}


VB.NET

Public Class MyClass
  Public Function OneMethod() As String
    Dim MyString As String = "hello"
    Return MyString
  End Function
  Public Function TwoMethod() As String
    Return MyString ' throws an exception
  End Function
End Class


     Python   SQL   Java   php   Perl 
     game development   web development   internet   *nix   graphics   hardware 
     telecommunications   C++ 
     Flash   Active Directory   Windows