Can someone please explain the following constructor syntax to me. I haven’t come across it before and noticed it in a colleagues code.
public Service () : this (Service.DoStuff(), DoMoreStuff())
{ }
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
It chains to another constructor in the same class. Basically any constructor can either chain to another constructor in the same class using
: this (...), or to a constructor in the base class using: base(...). If you don’t have either, it’s equivalent to: base().The chained constructor is executed after instance variable initializers have been executed, but before the body of the constructor.
See my article on constructor chaining or the MSDN topic on C# constructors for more information.
As an example, consider this code:
The
Mainmethod calls the parameterless constructor inDerivedClass. That chains to the one-parameter constructor inDerivedClass, which then chains to the two-parameter constructor inBaseClass. When that base constructor completes, the one-parameter constructor inDerivedClasscontinues, then when that finishes, the original parameterless constructor continues. So the output is: