Calling constructor from other constructor in same class

C#Constructor

C# Problem Overview


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

C# Solutions


Solution 1 - C#

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][1] [1]: http://www.csharp411.com/constructor-chaining/

Solution 2 - C#

Yes, you'd use the following

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

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

Solution 3 - C#

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).

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionRobbert DamView Question on Stackoverflow
Solution 1 - C#GishuView Answer on Stackoverflow
Solution 2 - C#Matthew DresserView Answer on Stackoverflow
Solution 3 - C#ThomasView Answer on Stackoverflow