}
Instead of setting the properties individually in each constructor, each constructor itself sets some of the properties for other constructors. A more efficient way would be for some constructors to call the other constructors to set some of the properties. That would prevent a duplication of code that does the same thing. The Contact
class could be rewritten like this:
public class Contact {
//...
//---first constructor---
public Contact() {
this.ID = 9999;
}
//---second constructor---
public Contact(int ID) {
this.ID = ID;
}
//---third constructor---
this.FirstName = FirstName;
this.LastName = LastName;
}
//---fourth constructor---
this.Email = Email;
}
}
In this case, the fourth constructor is calling the third constructor using the this
keyword. In addition, it is also passing in the arguments required by the third constructor. The third constructor in turn calls the second constructor. This process of one constructor calling another is call
To prove that constructor chaining works, use the following statements:
Contact c1 = new Contact(1234, 'Wei-Meng', 'Lee', '[email protected]');
Console.WriteLine(c1.ID); //---1234---
Console.WriteLine(c1.FirstName); //---Wei-Meng---
Console.WriteLine(c1.LastName); //---Lee---
Console.WriteLine(c1.Email); //[email protected]
To understand the sequence of the constructors that are called, insert the following highlighted statements:
class Contact {
//...
//---first constructor---
public Contact() {
this.ID = 9999;
}
//---second constructor---
public Contact(int ID) {
this.ID = ID;
}
//---third constructor---
public Contact(int ID, string FirstName, string LastName) :
this(ID) {
this.FirstName = FirstName;
this.LastName = LastName;
}
//---fourth constructor---
public Contact(int ID, string FirstName, string LastName, string Email) :
this(ID, FirstName, LastName) {
this.Email = Email;
}
}
The statement:
Contact c1 = new Contact(1234, 'Wei-Meng', 'Lee', '[email protected]');
prints the following output:
Second constructor
Third constructor
Fourth constructor
If your class has static members, it is only sometimes necessary to initialize them before an object is created and used. In that case, you can addContact
class has a public static
member count
to record the number of the Contact object created. You can add a static constructor to initialize the static member, like this:
public class Contact {
//...
public static int count;