CHAPTER 5 UNDERSTANDING ENCAPSULATION
an object using the new keyword. However, unlike a “normal” method, constructors never have a return
value (not even void) and are always named identically to the class they are constructing.
The Role of the Default Constructor
Every C# class is provided with a freebee default constructor that you may redefine if need be. By
definition, a default constructor never takes arguments. After allocating the new object into memory, the
default constructor ensures that all field data of the class is set to an appropriate default value (see
Chapter 3 for information regarding the default values of C# data types).
If you are not satisfied with these default assignments, you may redefine the default constructor to
suit your needs. To illustrate, update your C# Car class as follows:
class Car
{
// The 'state' of the Car.
public string petName;
public int currSpeed;
// A custom default constructor.
public Car()
{
petName = "Chuck";
currSpeed = 10;
}
...
}
In this case, we are forcing all Car objects to begin life named Chuck at a rate of 10 mph. With this,
you are able to create a Car object set to these default values as follows:
static void Main(string[] args)
{
Console.WriteLine("***** Fun with Class Types *****\n");
// Invoking the default constructor.
Car chuck = new Car();
// Prints "Chuck is going 10 MPH."
chuck.PrintState();
...
}
Defining Custom Constructors
Typically, classes define additional constructors beyond the default. In doing so, you provide the object
user with a simple and consistent way to initialize the state of an object directly at the time of creation.
Ponder the following update to the Car class, which now supports a total of three constructors:
class Car
{
// The 'state' of the Car.
public string petName;
167