What is Constructor Chaining?

 Posted by Kishork80 on 2/26/2011 | Category: .NET Framework Interview questions | Views: 24961 | Points: 40
Answer:

We can chain the call of constructor from child class to base class depending on our requirement. This concept makes sure that the matching base class constructor must be called based on the parameter passed to the child class constructor.

Example:

namespace ConsoleApplication1

{
class A
{
public A(){
Console.WriteLine("Constructor A.");
}
public A(string s){
Console.WriteLine("Constructor A with parameter = {0}",s);
}
public A(string s,string t){
Console.WriteLine("Constructor A with parameter = {0} & {1}", s,t);
}
}

class B:A
{
public B():base(){
Console.WriteLine("Constructor B.");
}
public B(string s):base(s){
Console.WriteLine("Constructor B with parameter = {0}", s);
}
public B(string s, string t):base(s,t){
Console.WriteLine("Constructor B with parameter = {0} & {1}", s, t);
}
}
class Program
{
static void Main(string[] args)
{
B b1 = new B();
B b2 = new B("First Parameter ", "Second Parameter");

Console.Read();
}
}
}


Output:
Constructor A.
Constructor B.
Constructor A with parameter = First Parameter & Second Parameter
Constructor B with parameter = First Parameter & Second Parameter


Asked In: Many Interviews | Alert Moderator 

Comments or Responses

Posted by: SheoNarayan on: 2/27/2011 | Points: 10
Dear Kishore,

I would appreciate if you can keep the Code snippets in the Code block (Select code snippets and click on the Code toolbar icon). This would make the code easily readable and understandable.

Thanks
Posted by: Chvrsri on: 2/28/2011 | Points: 10
Hi Kishore,

I have placed your code snippet in the code block using my admin panel.
This is a gentle reminder for you that, from next time onwards please place the code snippets in the code block given.

Thanks.

Login to post response

More Interview Questions by Kishork80