I wonder if anyone can explain the syntax in one line of this snippet of code:
public class ContactController : Controller
{
private IContactManagerRepository _repository;
**public ContactController()
: this(new EntityContactManagerRepository())**
{}
public ContactController(IContactManagerRepository repository)
{
_repository = repository;
}
The bit I am particularly interested in is the first constructor. I understand from the article I got it from (http://www.asp.net/learn/mvc/tutorial-29-cs.aspx - listing 3) that the first constructor calls the second, and intellisense tells me when I hover over this(new EntityContactManagerRepository()) that it does indeed refer to the second constructor. But I haven't seen a constructor with a colon after it before. I know that the colon in the class declaration tells the compiler that ContactController inherits from Controller, but what does the colon in the constructor do?
As you've said, it just calls the other constructor as the first part of execution. An alternative is to use base which calls a constructor in the base class instead. The language specification uses the term constructor initializer for this call. There's always something like this - if you don't specify anything, it's equivalent to a call to base(). In other words:
public Foo(int x)
is equivalent to
public Foo(int x) : base()
In both cases the base class's parameterless constructor is called before the body of the Foo constructor is executed. The compiler makes sure that you don't get into an infinite loop - every (non-static) class has to have at least one constructor which calls the base class constructor; you always end up calling the base class constructor before the constructor body for "this" class executes.
Unlike in Java, however, the instance variable initializers are executed before the base class constructor calls.
See my article about constructor chaining for more information.
It is called constructor chaining. With that syntax you can call the constructor of the base class or another constructor of the current class.
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