Make an initializing constructor for a child class in C#

[initializing constructor]

An initializing constructor is a constructor that takes parameters to make it easy to initialize an object’s properties. This example shows how to reuse a class’s initializing constructor for a child class.

The following Person class has an initializing constructor.

public class Person
{
    public string FirstName, LastName, Street, City, State, Zip;

    // Initializing constructor.
    public Person(string firstName, string lastName,
        string street, string city, string state, string zip)
    {
        FirstName = firstName;
        LastName = lastName;
        Street = street;
        City = city;
        State = state;
        Zip = zip;
    }
}

The constructor simply saves its parameter values in the object’s properties.

The following code shows an Employee class that inherits from the Person class.

public class Employee : Person
{
    public string MailStop;

    // Initializing constructor.
    public Employee(string firstName, string lastName,
        string street, string city, string state,
        string zip, string mailStop)
        : base(firstName, lastName, street, city, state, zip)
    {
        MailStop = mailStop;
    }
}

Notice how this class’s initializing constructor uses the “: base” syntax to invoke its base class’s constructor. That not only saves some typing but it also lets the child class take advantage of whatever code is in the base class’s constructor. For example, the Person class might validate the data to ensure that the fields were non-blank, that the state and city were valid, and that the ZIP code was valid for the state and city. In that case, by invoking the parent class’s constructor the Employee class would gain the benefits of those validations.

In general it’s a good idea for child class constructors to invoke the parent class’s constructor even if it takes no parameters so the parent class can perform whatever initialization and validation it defines. Later, if you modify the parent class to add actions to its constructors, the child class automatically gets the advantage of those changes without requiring you to add new code to the child class. (In fact, if the parent class has a lot of child classes, it might be hard to remember to modify them all later.)


Download Example   Follow me on Twitter   RSS feed   Donate




This entry was posted in classes, OOP and tagged , , , , , , , , , , , , , , . Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *