Overloaded Constructors

  • Thread starter Thread starter Roger Webb
  • Start date Start date
R

Roger Webb

Hey All,

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
 
Roger,
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
 
Roger Webb said:
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

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;
}
}
 
Why drag another function into it?

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.



Mattias
 
Back
Top