150

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#?

ShuggyCoUk
  • 36,004
  • 6
  • 77
  • 101
Robbert Dam
  • 4,027
  • 10
  • 39
  • 58

3 Answers3

229

Append :this(required params) at the end of the constructor 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

user2428118
  • 7,935
  • 4
  • 45
  • 72
Gishu
  • 134,492
  • 47
  • 225
  • 308
33

Yes, you'd use the following

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

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

    }
}
Matthew Dresser
  • 11,273
  • 11
  • 76
  • 120
  • 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 May 06 '09 at 14:31
  • Yup, sorry about that. Corrected now. – Matthew Dresser May 06 '09 at 14:33
15

The order of constructor evaluation must also be taken into consideration when chaining constructors:

To borrow from Gishu's answer, a bit (to keep code somewhat similar):

public Test(bool a, int b, string c)
    : this(a, b)
{
    this.C = c;
}

private Test(bool a, int b)
{
    this.A = a;
    this.B = b;
}

If we change the evalution performed in the private constructor, slightly, we will see why constructor ordering is important:

private Test(bool a, int b)
{
    // ... remember that this is called by the public constructor
    // with `this(...`

    if (hasValue(this.C)) 
    {  
         // ...
    }

    this.A = a;
    this.B = b;
}

Above, I have added a bogus function call that determines whether property C has a value. At first glance, it might seem that C would have a value -- it is set in the calling constructor; however, it is important to remember that constructors are functions.

this(a, b) is called - and must "return" - before the public constructor's body is performed. Stated differently, the last constructor called is the first constructor evaluated. In this case, private is evaluated before public (just to use the visibility as the identifier).

Thomas
  • 6,291
  • 6
  • 40
  • 69