BLOG.CSHARPHELPER.COM: Make an initializing constructor for a child class in C#
Make an initializing constructor for a child class in C#
The example Give a class auto implemented properties and initializing constructors in C# shows how to make a constructor that initializes a class'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 following code shows an Employee class that inherits from the Person class.
public class Employee : Person { public string MailStop;
Notice how this class's initializing constructor invokes its base class's constructor by using the ": base" syntax. 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, the city and state 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.
Comments