Information Technology Reference
In-Depth Information
Accessing Members from Outside the Class
To access a public instance member from outside the class, you must include the variable
name and the member name, separated by a period (dot). This is called
dot-syntax notation
;
it will be discussed in more detail later.
For example, the second line of the following code shows an example of accessing a
method from outside the class:
DaysTemp MyDt = new DaysTemp(); // Create an object of the class.
float FValue = MyDt.Average(); // Access it from outside.
↑
↑
Variable name Member name
As an example, the following code declares two classes:
DaysTemp
and
Program
.
The two ields in
DaysTemp
are declared
public
, so they can be accessed from outside
the class.
Method
Main
is a member of class
Program
. It creates a variable and object of class
DaysTemp
, and assigns values to the fields of the object. It then reads the values of the
fields and prints them out.
class DaysTemp // Declare class DaysTemp
{
public int High = 75;
public int Low = 45;
}
class Program // Declare class Program.
{
static void Main()
{
Variable name
↓
DaysTemp Temp = new DaysTemp(); // Create the object.
Variable name and field
↓
Temp.High = 85; // Assign to the fields.
Temp.Low = 60;
Variable name and field
↓
Console.WriteLine("High: {0}", Temp.High ); // Read from fields.
Console.WriteLine("Low: {0}", Temp.Low );
}
}
This code produces the following output:
High: 85
Low: 60