What is usage of "Constructor Chain"?
You use it for calling one constructor from another constructor.
How can implement "Constructor Chain"?
Use ": this (yourProperties)" keyword after definition of constructor. for example:
Class MyBillClass
{
private DateTime requestDate;
private int requestCount;
public MyBillClass()
{
/// ===== we naming "a" constructor ===== ///
requestDate = DateTime.Now;
}
public MyBillClass(int inputCount) : this()
{
/// ===== we naming "b" constructor ===== ///
/// ===== This method is "Chained Method" ===== ///
this.requestCount= inputCount;
}
}
Why is it useful?
Important reason is reduce coding, and prevention of duplicate code. such as repeated code for initializing property
Suppose some property in class must be initialized with specific value (In our sample, requestDate). And class have 2 or more constructor. Without "Constructor Chain", you must repeat initializaion code in all constractors of class.
How it work? (Or, What is execution sequence in "Constructor Chain")?
in above example, method "a" will be executed first, and then instruction sequence will return to method "b".
In other word, above code is equal with below:
Class MyBillClass
{
private DateTime requestDate;
private int requestCount;
public MyBillClass()
{
/// ===== we naming "a" constructor ===== ///
requestDate = DateTime.Now;
}
public MyBillClass(int inputCount) : this()
{
/// ===== we naming "b" constructor ===== ///
// ===== This method is "Chained Method" ===== ///
/// *** --- > Compiler execute "MyBillClass()" first, And then continue instruction sequence from here
this.requestCount= inputCount;
}
}
0
and""
) in more than one place (less chance for an error). For example:public Foo(int id) : this () { this.id = id; }
? Alternatively, I was also considering:public Foo(int id) : this ("") { this.id = id; }
. Just looking for the best logical way to chain them, appreciate any thoughts. – Hasa