tags:

views:

546

answers:

2

I have a class with 2 constructors:

public class Lens
{
    public Lens(string parameter1)
    {
        //blabla
    }

    public Lens(string parameter1, string parameter2)
    {
       // want to call constructor with 1 param here..
    }
}

I want to call the first constructor from the 2nd one. Is this possible in C#?

+19  A: 

Append :this(reqd params) at the end of the ctor to do 'constructor chaining'

public Test( bool a, int b, string c )
    : this( a, b )
{
    this.m_C = c;
}
public Test( bool a, int b, float d )
    : this( a, b )
{
    this.m_D = d;
}
private Test( bool a, int b )
{
    this.m_A = a;
    this.m_B = b;
}

Source Courtesy of csharp411.com

Gishu
That was pretty easy.. thanks!
Robbert Dam
+5  A: 

Yes, you'd use the following

public class Lens
{
    public Lens(string parameter1)
    {
       //blabla
    }

    public Lens(string parameter1, string parameter2) : this(parameter1)
    {

    }
}
mdresser
I think what would happen in the second constructor is that you'd create a local instance of Lens which goes out of scope at the end of the constructor and is NOT assigned to "this". You need to use the constructor chaining syntax in Gishu's post to achieve what the question asks.
Colin Desmond
Yup, sorry about that. Corrected now.
mdresser