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