can I call from one constructor another constructor ?

  • Thread starter Thread starter Paul
  • Start date Start date
P

Paul

public class A
{
public A ()
{
// here I would like to call the second version of _ctor, how to
accomplish this ?
}

public A (int a, int b, int c)
{
// some code
}
}

Thanks for any advice,
Paul
 
Paul.

use this to reference current instance.

E.g.

public A() : this(1,2,3) {
....
}

HTH
Alex
 
You cannot. You will have to move the code in the second constructor into a
function, called 'Initialize' for example, and then invoke that function
from both constructors.

You can, however, invoke inherited contructors in the constructor signature
using the base keyword, eg:

public A (int param1, string param2) : base(param1, param2)
{
...
}
 
do it like this:
public A() : this(1, 2, 3)
{
// other constructor will be called before anything
// happens in this one.
}

Chris
 
John Wood said:
You cannot. You will have to move the code in the second constructor into a
function, called 'Initialize' for example, and then invoke that function
from both constructors.

Yes you can - just as your code below, but using "this" instead of
"base".
You can, however, invoke inherited contructors in the constructor signature
using the base keyword, eg:

public A (int param1, string param2) : base(param1, param2)
{
...
}

Point of pedantry: constructors aren't inherited. That invokes the base
constructor.
 
Yes you can - just as your code below, but using "this" instead of
Yeah true you can (I admit I forgot), but I rarely use that because you have
little control over when the referenced constructor is called (it always
runs before the constructor body).
 
John Wood said:
Yeah true you can (I admit I forgot), but I rarely use that because you have
little control over when the referenced constructor is called (it always
runs before the constructor body).

That doesn't mean it's not useful though. I use it all the time when
providing constructs which effectively default various values - each
constructor calls a version with more parameters, either directly going
to the "full" one or going in stages. I believe this is fairly common.
 
I still don't get why they didn't add optional parameters in C#...
Constructor overloads can get pretty messy, given all the permutations you
have to provide.
 
Incidentally, I typically use the essence pattern for constructing complex
objects now.. saves having all those overloads cluttering the class.
 
John Wood said:
I still don't get why they didn't add optional parameters in C#...
Constructor overloads can get pretty messy, given all the permutations you
have to provide.
Because, IMHO, Optional parameters end up being more complex in practice.
They pretty much hide whats actually going on: an optional parameter hides
values, meaning you have to rely on documentation to understand whats being
passed as well as to what the passed values mean as far as behavior goes.
That isn't particularly pleasent and doesn't tend to be that easy to debug
or maintain.
Badly written methods that use optional parameters can be more complex than
a set of overloads(a few dozen if statements in one method redirecting to
sub methods or whatever, based entirely on which parameters were provided).
Another particular problem is that optional parameters do *nothing* to
express constraints. A method with 4 parameters, of which any three can be
provided or where all 4 can be provided or only 2 can, or whatever just
doesn't work. Overloads are the proper choice here, optional parameters are
not substitutes for functional permutation, they are only for situations
where you don't wish to pass a parameter and are happy with the default
value. Note I would consider it bad practice to check an optional parameter
for null and then assign a property a generic value based on that null(ya
know, new MyObject()).
Optional parameters also have a particular limitation in that the default
value takes away one possible state. Its usually irrelevent, but being able
to differentiate between a default value x and the literal value y that
happens to be equal to x may be relevent, especially if you are using
reference types(strings most likely). This manifests in nullablity as
well(as best as I remember, the runtime doesn't allow that level of
flexibilty but I may be wrong. These are conceptual arguments not
implementation specific).

I also think that methods like MyMethod(a,,,,,,4,,,83,c) are pretty
unreadable.

Beyond that, the one implementation specific issue: optional parameters
don't version well. You have to recompile client code whenever the parameter
values change as they are inserted into calling code directly.

Put all that together and I argue that optional parameters should rarely, if
ever, be used. There are just too many problems, too many tricks, and far to
many oppurtunities for misuse(and, examining history, misuse is the law of
the land).
 
They pretty much hide whats actually going on: an optional parameter hides
values, meaning you have to rely on documentation to understand whats being
passed as well as to what the passed values mean as far as behavior goes.
<<

Right but the same goes for overloaded methods... you're no longer providing
the parameter, so what would it default to? In VIsual Basic, for example,
you can specify the default value as part of the method signature. As such,
it would be displayed in intellisense. That's something which is impossible
with overloading -- because the defaulting is hidden away in code that's not
visible without manual documentation.
express constraints. A method with 4 parameters, of which any three can be
provided or where all 4 can be provided or only 2 can, or whatever just
doesn't work. <<

I agree here, sometimes parameters aren't just optional they're mutually
exclusive, in combinations that are impossible to represent with optional
parameters. However this is an obvious candidate for overloading... but that
doesn't mean we shouldn't have optional parameters for all other situations,
they easily complement one another.
null and then assign a property a generic value based on that null(ya know,
new MyObject()). <<

Yeah of course, I don't think anyone would advocate that, another good
reason to have optional parameters, rather than letting people try to
synthesize a half-baked optional parameter implementation themselves.
value takes away one possible state...able to differentiate between a
default value x and the literal value y that happens to be equal to x may be
relevent <<

Yeah, this can and has been solved in Visual Basic, where you have the
IsMissing keyword that indicates whether or not a parmeter was actually
specified. eg. if (isMissing(price)) price = 23;
unreadable. <<

VBA actually has some nice optional parameter syntax, it allows you to
specify the name of the parameter(s) in the method call, eg. MyMethod(
category:=CitrusFruit, price:=1.45, weight:=6 );
C# could quite easily adopt this syntax, and allow it for non-optional
paramaterized methods also.
don't version well. You have to recompile client code whenever the parameter
values change as they are inserted into calling code directly. <<

I think the above method of specifying optional parameters would version
quite well, so long as a parameter names didn't change. In fact it would
probably version better than a regular method (because parameter specifying
to parameter signature binding is explicit).

--
John Wood
EMail: first name, dot, last name, at priorganize.com

Daniel O'Connell said:
John Wood said:
I still don't get why they didn't add optional parameters in C#...
Constructor overloads can get pretty messy, given all the permutations you
have to provide.
Because, IMHO, Optional parameters end up being more complex in practice.
They pretty much hide whats actually going on: an optional parameter hides
values, meaning you have to rely on documentation to understand whats being
passed as well as to what the passed values mean as far as behavior goes.
That isn't particularly pleasent and doesn't tend to be that easy to debug
or maintain.
Badly written methods that use optional parameters can be more complex than
a set of overloads(a few dozen if statements in one method redirecting to
sub methods or whatever, based entirely on which parameters were provided).
Another particular problem is that optional parameters do *nothing* to
express constraints. A method with 4 parameters, of which any three can be
provided or where all 4 can be provided or only 2 can, or whatever just
doesn't work. Overloads are the proper choice here, optional parameters are
not substitutes for functional permutation, they are only for situations
where you don't wish to pass a parameter and are happy with the default
value. Note I would consider it bad practice to check an optional parameter
for null and then assign a property a generic value based on that null(ya
know, new MyObject()).
Optional parameters also have a particular limitation in that the default
value takes away one possible state. Its usually irrelevent, but being able
to differentiate between a default value x and the literal value y that
happens to be equal to x may be relevent, especially if you are using
reference types(strings most likely). This manifests in nullablity as
well(as best as I remember, the runtime doesn't allow that level of
flexibilty but I may be wrong. These are conceptual arguments not
implementation specific).

I also think that methods like MyMethod(a,,,,,,4,,,83,c) are pretty
unreadable.

Beyond that, the one implementation specific issue: optional parameters
don't version well. You have to recompile client code whenever the parameter
values change as they are inserted into calling code directly.

Put all that together and I argue that optional parameters should rarely, if
ever, be used. There are just too many problems, too many tricks, and far to
many oppurtunities for misuse(and, examining history, misuse is the law of
the land).
 
Right but the same goes for overloaded methods... you're no longer
providing
the parameter, so what would it default to? In VIsual Basic, for example,
you can specify the default value as part of the method signature. As
such,
it would be displayed in intellisense. That's something which is
impossible
with overloading -- because the defaulting is hidden away in code that's
not
visible without manual documentation.

Not quite. Because overloaded methods don't take those parameters, they
simply don't matter and aren't necessarily even used. When it comes to
overloads functionality definition is all that matters. I don't think the
same applies with defaults, as the actual *value* of a default is passed to
the method.
express constraints. A method with 4 parameters, of which any three can be
provided or where all 4 can be provided or only 2 can, or whatever just
doesn't work. <<

I agree here, sometimes parameters aren't just optional they're mutually
exclusive, in combinations that are impossible to represent with optional
parameters. However this is an obvious candidate for overloading... but
that
doesn't mean we shouldn't have optional parameters for all other
situations,
they easily complement one another.

I don't agree they easily compliment eachother. I would say the usage of
optional parameters is pretty constrained to *one* type of usage, but is
generally abused to bend them into another type. At the least, if a change
in the implementation of a optional method changes to where different
parameter combinations requires different logic, you can't easily change the
interface. With overloaded methods you don't have to change anything, as
long as that predefined pair exists already.

This goes against versioning.
null and then assign a property a generic value based on that null(ya
know,
new MyObject()). <<

Yeah of course, I don't think anyone would advocate that, another good
reason to have optional parameters, rather than letting people try to
synthesize a half-baked optional parameter implementation themselves.

I don't know, some might. No optional means people write overloads or write
bad interfaces that look bad(I do think optional is one major failing of vb,
and a significant cause of the problems with VB libraries, the interfaces
are terrible but they dont' look that way to vb devs).

You should also probably absolutly avoid using optional parameters in
interfaces, abstract or virtual methods when you can't be absolutely
*CERTAIN* that no inheriter will ever have any interest in performing
anything but basic mapping. An optional parameter in an interface severely
constrains the actual possible implementation logic or force the bad designs
I've discussed. Its not a very good idea.
value takes away one possible state...able to differentiate between a
default value x and the literal value y that happens to be equal to x may
be
relevent <<

Yeah, this can and has been solved in Visual Basic, where you have the
IsMissing keyword that indicates whether or not a parmeter was actually
specified. eg. if (isMissing(price)) price = 23;

I did some checking, IsMissing is *not* supported in VB.NET, as the CLS
doesn't directly support optional parameters. Default values are simply
metadata applied to a method, each language is responsible for loading those
values *directly* into client code, the runtime is entirely uninvolved.
unreadable. <<

VBA actually has some nice optional parameter syntax, it allows you to
specify the name of the parameter(s) in the method call, eg. MyMethod(
category:=CitrusFruit, price:=1.45, weight:=6 );
C# could quite easily adopt this syntax, and allow it for non-optional
paramaterized methods also.

It could, but I think its ugly syntax as well. It doesn't solve anything and
it has the additional downside of hiding the fact that the method actually
takes 15 parameters.

I also worry that such syntax promotes writting bad method interfaces(as
I've expressed before). Instead of writing an overload, people would prefer
to modify the signature of the one method and simply have one huge method so
they never have to change client code. This is another major issue.
don't version well. You have to recompile client code whenever the
parameter
values change as they are inserted into calling code directly. <<

I think the above method of specifying optional parameters would version
quite well, so long as a parameter names didn't change. In fact it would
probably version better than a regular method (because parameter
specifying
to parameter signature binding is explicit).

It doesn't solve the fact that client code has optionals baked in. That
there is no way to differentiate between a default parameter value and the
same value passed in(without significant changes to the runtime).
Don't forget the CLS. To support optional parameters to the extent you want
would either require adding support to the CLS(and every language) or
removing it totally(as it stands its optional) as every langauge would have
to support the new calling semantics involved to allow making calls with
no-value support(some form of special stack value would have to be used to
specify no value was passed, vs default value or a given value).
The results aren't pleasent for a feature that has limited usage, IMHO. As
I've shown, they are only of value in methods that won't be overloaded and
potentially constructors...what are the real values, outside of simply
making things easier in those rather rare situations where you can be sure
it'll never break anything?
 
Not quite. Because overloaded methods don't take those parameters, they
simply don't matter and aren't necessarily even used. When it comes to
overloads functionality definition is all that matters. I don't think the
same applies with defaults, as the actual *value* of a default is passed to
the method. <<

That's true for the instance where you actually *want* an overload. I think
there's quite a distinction between parameters that are truly optional
(and/or can be defaulted), and method signature permutations that call for
straight forward overloading.

If you agree with that, then you'd understand how intellisense would be
available to display the default values of missing parameters, and this
wouldn't be so easily achieved with overloaded functions trying to mimick
optional parameters. How much of my day do I spend looping through all the
permutations of parameters in overloads of a method, just to find the
combination I want? Some methods have 20 or more permutations!
optional parameters is pretty constrained to *one* type of usage, but is
generally abused to bend them into another type. <<

Anything can be abused if poorly understood, I don't think that's an
argument to throw out the feature for good. Interfaces can be used where an
abstract base class is used, methods can have out parameters where a return
value should be used, methods can be defined where properties should be
defined... etc. etc.
interfaces, abstract or virtual methods when you can't be absolutely
*CERTAIN* that no inheriter will ever have any interest in performing
anything but basic mapping. <<

I tend to agree with that. Although I don't think the compiler should
necessarily enforce it.

Yeah I was aware of that.. I was referring to vb 6.
and the same value passed in(without significant changes to the runtime). <<

I understand there are certainly CLS-related issues, cross language
interoperation issues. They had the same issues with implementing optional
parameters in COM.. and what did they do? They mandate that all optional
parameters are variants and therefore typeless, and a 'not specified' value
of the variant is used to specify missing parameters.

While I wouldn't advocate such a solution in the CLR, a variation on that
might be possible. For languages that have not been upgraded to support
optional parameters, the parameters are passed in as objects, and a special
object instance 'Missing' can be used for missing parameters.

For languages that do support optional parameters, extra meta data in the
method signature can be used to determine the actual type of the parameter,
along with information on the default values used if the value isn't
specified. This can be displayed in intellisense, and the language can be
extended to support a parameter-specifying syntax as mentioned from VBA
above.
and potentially constructors <<

I'm not convinced. There are a vast number of patterns used in the plethora
of software applications available today, it would be difficult or
impossible for anyone to say that's the case.

Construction definitely (although as I mentioned in another post, I have
used the essence pattern to overcome some of these limitations).

Elsewhere? Well, look at dispatch based COM interfaces throughout Microsoft
products. Every other method in the object model uses optional parameters.
Take Excel for example. A method such as AutoFill on a sheet, taking the
destination as the first parameter, followed by the optional type of the
auto-fill operation as an enumerator. It tells you in intellisense what the
default value is, and that seems sensible to me. You just couldn't do that
with overloading -- how would I know what it does if it's not specified?
 
I still don't get why they didn't add optional parameters in C#...
Constructor overloads can get pretty messy, given all the permutations you
have to provide.

coming from a language which didnt have the overload concept (vb old) iam
thankfull everyday that C# does.

all it done was force brain bending logic to get things going.
 
VBA actually has some nice optional parameter syntax, it allows you to
specify the name of the parameter(s) in the method call, eg. MyMethod(
category:=CitrusFruit, price:=1.45, weight:=6 );

iirc vb had it too, not that it matters im too lazy to type out all that.
C# could quite easily adopt this syntax, and allow it for non-optional
paramaterized methods also.

god i hope not.
 
The short answer is no. The constructor constructs an instance of a class. A more correct 'if there is one' version of the example you have provided would be:

public class A
{
private int a = 0;
private int b = 0;
private int c = 0;

public A ()
{

// a, b, c are initialized by the default values. Calling another constructor
is not necessary.. }

public A (int a, int b, int c)
{
_a = a;
_b = b;
_c = c;
// Whatever code you want here.
}

public int A {
get {
return _a;
}
set {
_a = value;
}
}

// Accessors for B and C would be here
}

Hope this helps.
 
A slightly longer answer is yes, by providing default values:

public class A {

public A(int a, int b, int c) {
...
}
public A() : this(1, 2, 3) {
...
}

}
 
I know that this might be getting away from the original post, but I have a question about optional paramters in C#.

I originally developed a COM DLL using VB.NET which had an optional parameter in one of the methods. I ported the entire project to C# (as I decided C# was the way to go) but I was unable to work out how to redefine the COM interface in C# with an optional COM parameter.

In the end the COM interface was defined in VB.NET and the rest of the project was written using C#. I know that this isn't a big deal, but it's been bugging me for a while now. Does anyone have any ideas on how to do this?

Thanks.

John Wood said:
Incidentally, I typically use the essence pattern for constructing complex
objects now.. saves having all those overloads cluttering the class.
 
Back
Top