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#?
The invocation of one constructor from another constructor within the same class or different class is known as constructor chaining in Java. If we have to call a constructor within the same class, we use 'this' keyword and if we want to call it from another class we use the 'super' keyword.
Example 1: Java program to call one constructor from another Here, you have created two constructors inside the Main class. Inside the first constructor, we have used this keyword to call the second constructor. this(5, 2); Here, the second constructor is called from the first constructor by passing arguments 5 and 2.
Java Constructor Chaining in the Same Class You can create multiple constructors in the same class, each with a different number of arguments that it accepts. To call one of the constructors in another constructor (of the same class), use the keyword this().
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
Yes, you'd use the following
public class Lens
{
public Lens(string parameter1)
{
//blabla
}
public Lens(string parameter1, string parameter2) : this(parameter1)
{
}
}
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With