Can I call another constructor from a constructor?

  • Thread starter Thread starter Tom
  • Start date Start date
T

Tom

Is it possible to do something like this:

public class CommentDlg : System.Windows.Forms.Form
{

[...]

public CommentDlg()
{
InitializeComponent();
}

public CommentDlg(string comment)
{
CommentDlg(); // <<<--- this generates a compile error
Comment = comment;
}

[...]

}
 
public class Test
{
public Test()
{
Console.WriteLine("Test()");
}
public Test(string text) : this()
{
Console.WriteLine("Test(string text)");
}
}

There are cases when you may want a private method that contains shared
logic among many contructors. Then just call that from each constructor.
If it throws and exception, so does the constructor (if you don't catch it.)
 
Hi Tom!
You can do it like this:

public CommentDlg()
{
// this is my default constructor
}
public CommentDlg(string comment) : this ()
{
// some code here
}

when you call CommentDlg(string comment) constructor, CommentDlg() will
execute first and then CommentDlg(string comment)...

ofcource, you can call other constructor too, like this:

public CommentDlg() {}
public CommentDlg(string comment) : this () {}
public CommentDlg(string someData, int hello) : this (someData) {}

if you call public CommentDlg(string someData, int hello), execution order
is:
1. public CommentDlg() {}
2. public CommentDlg(string comment) : this () {}
3. public CommentDlg(string someData, int hello) : this (someData) {}


hope this helps...
Jeti
 
Back
Top