Information Technology Reference
In-Depth Information
Instance Constructors
An instance constructor is a special method that is executed whenever a new instance of a class
is created.
A constructor is used to initialize the state of the class instance.
If you want to be able to create instances of your class from outside the class, you need
to declare the constructor
public
.
Figure 6-12 shows the syntax of a constructor. A constructor looks like the other methods
in a class declaration, except for the following:
The name of the constructor is the same as the name of the class.
A constructor cannot return a value.
Figure 6-12.
Constructor declaration
For example, the following class uses its constructor to initialize its fields. In this case, it
has a field called
TimeOfInstantiation
that is initialized with the current date and time.
class MyClass
{
DateTime TimeOfInstantiation; // Field
...
public MyClass() // Constructor
{
TimeOfInstantiation = DateTime.Now; // Initialize field
}
...
}
■
Note
Having finished the section on static properties, take a closer look at the line that initializes
TimeOfInstantiation
. The
DateTime
class is from the BCL, and
Now
is a
static property
of the
DateTime
class. The
Now
property creates a new instance of the
DateTime
class, initializes it with the
current date and time from the system clock, and returns a reference to the new
DateTime
instance.