294
LESSON 24 InItIalIzIng Objects
Note that the object’s Dispose method is called even if the program exits from the block due to
an exception.
INVOKING OTHER CONSTRUCTORS
You can give a class many different constructors as long as they have different parameter lists (so
C# can tell them apart). For example, you might give the
Person class a parameterless constructor;
a second constructor that takes first name and last name as parameters; and a third constructor that
takes first and last name, street, city, state, and ZIP Code as parameters.
Often when you give a class multiple constructors, some of them perform the same actions. In the
Person example, the constructor that initializes first name, last name, street, city, state, and ZIP
Code probably does the same things that the second constructor does to initialize just first and last
name (plus more).
You can also find overlapping constructor functionality when one class inherits from another. For
example, suppose the
Person class has FirstName and LastName properties. The Employee class
inherits from
Person and adds some other properties such as EmployeeId and MailStop. The
Person class’s constructor initializes the FirstName and LastName properties, something that the
Employee class’s constructors should also do.
Having several methods perform the same tasks makes debugging and maintaining code harder.
Fortunately, C# provides a way you can make one constructor invoke another.
To make a constructor invoke another in the same class, follow the constructor’s parameter declarations
with a colon and the keyword
this, passing this any parameters that the other constructor should
receive. For example, the following code shows three constructors for the
Person class that invoke each
other with the code that invokes other constructors is shown in bold:
// Parameterless constructor.
public Person()
{
// General initialization if needed ...
}
// Initialize first and last name.
public Person(string firstName, string lastName)
: this()
{
FirstName = firstName;
LastName = lastName;
}
// Initialize all values.
public Person(string firstName, string lastName, string street,
string city, string state, string zip)
: this(firstName, lastName)
{
FirstName = firstName;
LastName = lastName;
Street = street;
596906c24.indd 294 4/7/10 12:33:53 PM
Invoking Other Constructors
295
City = city;
State = state;
Zip = zip;
}
The first constructor is a parameterless constructor. In this example it doesn’t do anything.
The second constructor takes first and last names as parameters. The “
: this()” at the end of the
declaration means the constructor should invoke the parameterless constructor when it starts.
The third constructor takes name and address parameters. Its declaration ends with “
:
this(firstName, lastName)
” to indicate that the constructor should begin by calling the
second constructor, passing it the
firstName and lastName parameters. (That constructor in
turn invokes the parameterless constructor.)
You can use a similar syntax to invoke a parent class constructor by simply replacing the keyword
this with the keyword base.
For example, the
Employee class inherits from the Person class. The following code shows two of
the class’s constructors:
// Parameterless constructor.
public Employee()
: base()
{
}
// Initialize first and last name.
public Employee(string firstName, string lastName)
: base(firstName, lastName)
{
}
The first constructor is parameterless. It invokes its parent class’s parameterless constructor by using
: base().”
The second constructor takes first and last name parameters and invokes the
Person class’s constructor
that takes two strings as parameters.
Notice how the constructors invoke other constructors by using the keyword
this or base followed by a parameter list. C# uses the parameter list to decide
which constructor to invoke. Thats why you cannot have more than one con-
structor with the same kinds of parameters. For example, if two constructors
took a single
string as a parameter, how would C# know which one to use?
596906c24.indd 295 4/7/10 12:33:53 PM
296
LESSON 24 InItIalIzIng Objects
TRY IT
In this Try It, you enhance the Person, Employee, and Manager classes you built in one of the
Lesson 23 Try Its. You add constructors to make initializing objects easier and you add destruc-
tors so you can trace object destruction when the program ends.
You can download the code and resources for this Try It from the book’s web
page at
www.wrox.com or www.CSharpHelper.com/24hour.html. You can find
the files in the Lesson24 folder.
Lesson Requirements
Copy the program you built in the third Try It in Lesson 23 (or download the TryIt23c pro-
gram from the book’s web site).
Give the
Person class a parameterless constructor. Make it print a message to the Console
window indicating that a new
Person is being created.
Give the
Person class a constructor that initializes all of the class’s properties. Make it
invoke the parameterless constructor and display its own message.
Give the
Person class a destructor that displays a message in the Console window.
Make similar constructors and destructors for the
Employee and Manager classes.
Remove the buttons from the main form and make the program create
Person, Employee,
and
Manager objects using each of the constructors.
Run the program, close it, and examine the Console window messages to see if they make
sense.
Hints
Make the constructors invoke each other where possible to avoid duplicate work.
When you use parameterless constructors, use object initialization to set the objects’
properties.
Step-by-Step
Copy the program you built in the third Try It in Lesson 23 (or download the TrytIt23c pro-
gram from the book’s web site).
1. This is relatively straightforward.
596906c24.indd 296 4/7/10 12:33:54 PM
Try It
297
Give the
Person class a parameterless constructor. Make it print a message to the Console
window indicating that a new
Person is being created.
1. The Person class’s parameterless constructor should look something like this:
public Person()
{
Console.WriteLine(“Person()“);
}
Give the
Person class a constructor that initializes all of the class’s properties. Make it
invoke the parameterless constructor and display its own message.
1. This constructor should look something like this:
public Person(string rstName, string lastName,
string street, string city, string state, string zip)
: this()
{
FirstName = rstName;
LastName = lastName;
Street = street;
City = city;
State = state;
Zip = zip;
Console.WriteLine(“Person(parameters)“);
}
Give the
Person class a destructor that displays a message in the Console window.
1. This destructor should look something like this:
~Person()
{
Console.WriteLine(“~Person”);
}
Make similar constructors and destructors for the
Employee and Manager classes.
1. The following code shows the Employee class’s constructors and destructor:
public Employee()
: base()
{
Console.WriteLine(“Employee()“);
}
public Employee(int employeeId, string mailStop,
string rstName, string lastName, string street,
string city, string state, string zip)
: base(rstName, lastName, street, city, state, zip)
{
EmployeeId = employeeId;
MailStop = mailStop;
Console.WriteLine(“Employee(parameters)“);
}
596906c24.indd 297 4/7/10 12:33:54 PM
298
LESSON 24 InItIalIzIng Objects
~Employee()
{
Console.WriteLine(“~Employee”);
}
2. The following code shows the Manager class’s constructors and destructor:
public Manager()
: base()
{
DirectReports = new List<Employee>();
Console.WriteLine(“Manager()“);
}
public Manager(string departmentName, int employeeId,
string mailStop, string rstName, string lastName,
string street, string city, string state, string zip)
: base(employeeId, mailStop, rstName, lastName, street,
city, state, zip)
{
DepartmentName = departmentName;
Console.WriteLine(“Manager(parameters)“);
}
~Manager()
{
Console.WriteLine(“~Manager”);
}
Remove the buttons from the main form and make the main program create
Person,
Employee, and Manager objects using each of the constructors.
1. The following code creates objects in this way:
// Make the people.
private void Form1_Load(object sender, EventArgs e)
{
// Persons.
Console.WriteLine(“Creating Paula”);
Person paula = new Person()
{
FirstName = “Paula”,
LastName = “Perch”,
Street = “100 Ash Ave”,
City = “Bugsville”,
State = “CO”,
Zip = “82010”,
};
Console.WriteLine(“Creating Pete”);
Person pete = new Person(“Pete”, “Pearson”,
“2871 Arc St”, “Bugsville “, “CO”, “82010”);
// Employees.
Console.WriteLine(“Creating Edna”);
Employee edna = new Employee()
596906c24.indd 298 4/7/10 12:33:54 PM
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.189.186.109