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
In this case, there must a a second constructor which will accept two parameters - the return values of Service.DoStuff()
and DoMoreStuff()
. These two methods must be static methods.
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:
using System;
public class BaseClass
{
public BaseClass(string x, int y)
{
Console.WriteLine("Base class constructor");
Console.WriteLine("x={0}, y={1}", x, y);
}
}
public class DerivedClass : BaseClass
{
// Chains to the 1-parameter constructor
public DerivedClass() : this("Foo")
{
Console.WriteLine("Derived class parameterless");
}
public DerivedClass(string text) : base(text, text.Length)
{
Console.WriteLine("Derived class with parameter");
}
}
static class Test
{
static void Main()
{
new DerivedClass();
}
}
The Main
method calls the parameterless constructor in DerivedClass
. That chains to the one-parameter constructor in DerivedClass
, which then chains to the two-parameter constructor in BaseClass
. When that base constructor completes, the one-parameter constructor in DerivedClass
continues, then when that finishes, the original parameterless constructor continues. So the output is:
Base class constructor
x=Foo, y=3
Derived class with parameter
Derived class parameterless