
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 ...