Calling constructors
-
I have a form with three constructors each with a different signiture. i.e. public Form_1() ... public Form_1(string Name) ... public Form_1(string Name, int Number) ... How can i call the first constructor from the second and call the second from the third? At the minute I have to copy the common code into functions and call the functions but would prefer to call the constructors as i used to do in VB.Net. Thanks
-
I have a form with three constructors each with a different signiture. i.e. public Form_1() ... public Form_1(string Name) ... public Form_1(string Name, int Number) ... How can i call the first constructor from the second and call the second from the third? At the minute I have to copy the common code into functions and call the functions but would prefer to call the constructors as i used to do in VB.Net. Thanks
Use the 'this' keyword like this
public Form_1() : this(null) { //blah blah } public Form_1(string Name) : this(Name, 0) { } public Form_1(string Name, int Number) { }
-
Use the 'this' keyword like this
public Form_1() : this(null) { //blah blah } public Form_1(string Name) : this(Name, 0) { } public Form_1(string Name, int Number) { }
You've generated an extra call for no good reason. A better example would be:
public Form1() : this(null, 0)
{
}
public Form1(string name) : this(name, 0)
{
}
public Form1(string name, int number)
{
// Your implementation goes here.
}Why generate an extra call on the stack just to "redirect" to another method? This posting is provided "AS IS" with no warranties, and confers no rights. Software Design Engineer Developer Division Sustained Engineering Microsoft [My Articles] [My Blog]
-
You've generated an extra call for no good reason. A better example would be:
public Form1() : this(null, 0)
{
}
public Form1(string name) : this(name, 0)
{
}
public Form1(string name, int number)
{
// Your implementation goes here.
}Why generate an extra call on the stack just to "redirect" to another method? This posting is provided "AS IS" with no warranties, and confers no rights. Software Design Engineer Developer Division Sustained Engineering Microsoft [My Articles] [My Blog]
Heath Stewart wrote: Why generate an extra call on the stack just to "redirect" to another method? To avoid duplicating defaults and/or code (which could lead to inconsistent behavior). Actually, if you Google for it you'll notice that this is one of those religious things. Personally, I agree with you, with the added annoyance that single-stepping through code like this is really boring. Yes, even I am blogging now!