Information Technology Reference
In-Depth Information
Accessing Static Members from Outside the Class
In the previous chapter, you saw that dot-syntax notation is used to access instance members
from outside the class. Dot-syntax notation consists of listing the instance name, followed by a
dot, followed by the member name.
Static members, like instance members, are also accessed from outside the class using
dot-syntax notation. But instead of using the instance name , you must use the class name ,
as follows:
Class name
D.Mem2 = 5; // Accessing the static class member
Member name
Example of a Static Field
The following code expands the preceding class D by adding two methods:
￿
One method sets the values of the two data members.
￿
The other method displays the values of the two data members.
class D {
int Mem1;
static int Mem2;
public void SetVars(int v1, int v2) // Set the values
{ Mem1 = v1; Mem2 = v2; }
Access as if it were an instance field
public void Display( string str )
{ Console.WriteLine("{0}: Mem1= {1}, Mem2= {2}", str, Mem1, Mem2); }
}
Access as if it were an instance field
class Program {
static void Main()
{
D d1 = new D(), d2 = new D(); // Create two instances.
d1.SetVars(2, 4); // Set d1's values.
d1.Display("d1");
d2.SetVars(15, 17); // Set d2's values.
d2.Display("d2");
d1.Display("d1"); // Display d1 again and notice that the
} // value of static member Mem2 has changed!
}
Search WWH ::




Custom Search