know what employees to put in it. It can, however, initialize the DirectReports to an empty list as
shown in the following code:
class Manager : Person
{
List<Employee> DirectReports;
// Initialize the Manager.
public Manager()
{
DirectReports = new List<Employee>();
}
}
You implicitly invoke a parameterless constructor any time you create an object without using any
parameters. For example, the following code creates a new
Person object. When this code executes,
control jumps briefly to the parameterless constructor so it can prepare the object for use.
Person Fred = new Person();
Note that C# creates a default public parameterless constructor for you if you make a class that doesn’t
define any constructors explicitly. If you do give the class any constructors, however, C# doesn’t create
the default constructor. In that case, if you want a parameterless constructor, you must make it yourself.
Parameterized Constructors
Parameterless constructors are useful but fairly limited because they don’t have much information
to go by. To give a constructor more information, you can make it take parameters just like you can
with any other method.
One simple type of parameterized constructor uses its parameters to initialize properties. For example,
you could make a constructor for the
Person class that takes the person’s first and last names as
parameters. The constructor could then set the object’s
FirstName and LastName properties.
Why would you bother doing this when you could use an initializer? First, the syntax for using a
constructor is slightly more concise than initializer syntax. The following code uses a constructor
that takes eight parameters to initialize an
Employee’s properties:
Employee bob = new Employee(“Bob”, “Baker”, “200 Beach Blvd”,
“Bugsville”, “CO”, “82010”, 1002, “B-2”);
Compare this code to the earlier snippet that used initializers. This version is more concise, although
it’s less self-documenting because it doesn’t explicitly list the property names.
The second reason you might prefer to use a parameterized constructor instead of an initializer is that
a constructor can perform all sorts of checks that an initializer cannot. For example, a constructor can
validate its parameters against each other or against a database. An
Employee class’s constructor could
take an employee ID as a parameter and check in a database to verify that the employee really exists.
A constructor can also require that certain parameters be provided. For example, a
Person constructor
could require that the first and last name parameters be provided. If you rely on initializers, the pro-
gram could create a
Person that has no first or last name.
596906c24.indd 291 4/7/10 12:33:52 PM