Monday, December 22, 2008

A constructor can call another overloaded constructor

A constructor can call another overloaded constructer but there is a trick to make this call possible.

So in the following example when you create the instance of CallConstructor class without parameter constructor. This will internally call the constructor with parameter.

below is the code for the same.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace InterviewCodePractice.CallConstructor
{
public class CallConstructor
{
public CallConstructor()
: this(5)
{
System.Windows.Forms.MessageBox.Show("Default");
}
public CallConstructor(int i)
{
System.Windows.Forms.MessageBox.Show("parameter");
}
}
}


Output of the above problem will be
1. parameter will be printed in the messagebox.
2. Default will be printed in the messagebox.

No comments: