I looked through the news group and found a few threads on inheriting
constructors...which I dont think is what I want to do here... since I'm
dealing with issues between constructors of the same class.
Basically I would like to know how to call one constructor from another one.
I know that you can do something like A():this(10) to default a value,
however, I want to do a little more... something like
public class Class1
{
private int A;
public Class1(int x)
{
A = x;
}
public Class1(string x)
{
this(x.ToString());
}
public Class1(bool x)
{
if(x)
{ this(1);}
else
{ this(0);}
}
}
however, this gives a "Method Name Expected" Error on compile. I realize
this is a simple constructor... but is there a way I dont have to duplicate
the code that would go along with the Class1(int x) constructor in each
constructor?
- Roger Webb
>however, I want to do a little more...
Then put the code in a static method and call that.
> public Class1(string x)
> {
> this(x.ToString());
> }
Why call ToString on a string? Perhaps you mean Int32.Parse?
public Class1(string x) : this(Int32.Parse(x)) {}
> public Class1(bool x)
> {
> if(x)
> { this(1);}
> else
> { this(0);}
> }
static int Foo(bool x) { return x ? 1 : 0; }
public Class1(bool x) : this(Foo(x)) {}
Mattias
--
Mattias Sjögren [MVP] mattias @ mvps.org
http://www.msjogren.net/dotnet/ | http://www.dotnetinterop.com
Please reply only to the newsgroup.
You can't call another constructor except at the very start of the
constructor you're calling it from. You also can't call the same
constructor, which you're trying to in the second example. However, you
can do, say:
public class Class1
{
private int A;
public Class1(int x)
{
A = x;
}
public Class1(string x) : this (int.Parse(x))
{
}
public Class1(bool x) : this (x ? 1 : 0)
{
}
}
You could also call a static method using the parameters if you wanted
more complicated processing. For instance, the last constructor there
is equivalent to:
public Class1(bool x) : this (Foo(x))
{
}
static int Foo(bool x)
{
if (x)
{
return 1;
}
else
{
return 0;
}
}
--
Jon Skeet - <sk...@pobox.com>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too
Why drag another function into it?
public Class1(bool x) : this ( x ? 1 : 0)
{
}
--
Truth,
James Curran
[erstwhile VC++ MVP]
Home: www.noveltheory.com Work: www.njtheater.com
Blog: www.honestillusion.com Day Job: www.partsearch.com
Good point. I just wanted to demonstrate how to do it when a separate
function is needed, but you're right it isn't required here.