Information Technology Reference
In-Depth Information
Static Function Members
Besides static fields, there are also static function members.
Static function members, like static fields, are independent of any class instance. Even if
there are no instances of a class, you can call a static method.
Static function members cannot access instance members. They can, however, access
other static members.
For example, the following class contains a static field and a static method. Notice that the
body of the static method accesses the static field.
class X
{
static public int A; // Static field
static public void PrintValA() // Static method
{
Console.WriteLine("Value of A: {0}", A);
}
↑
}
Accessing the static field
The following code uses class
X
, defined in the preceding code. Figure 6-5 illustrates
the code.
class Program
{
static void Main()
{
X.A = 10; // Use dot-syntax notation
X.PrintValA(); // Use dot-syntax notation
}
↑
}
Class name
This code produces the following output:
Value of A: 10