tags:

views:

851

answers:

6

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?

+3  A: 

It is called constructor chaining. With that syntax you can call the constructor of the base class or another constructor of the current class.

idursun
+1  A: 

This feature is called Constructor Initializers.

CMS
A: 

The colon is used to indicate that you're calling another constructor from the same class (as in your example) or a constructor from the base class using :base(..args...)

This syntax is used to enforce that you're calling other constructors or base constructors before doing any extra work (i.e. it ensures the base class first initialization order).

Kurt Schelfthout
+4  A: 

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.

Jon Skeet
+1  A: 

You example uses constructor chaining. I.e. the default constructor calls a specific constructor with an argument on the same type. To do this, you use the this keyword with any arguments required as in your example.

A similar feature is the use of the base keyword. When you have a class hierarchy then you always call constructors for all the types in the hierarchy. So for instance if you have a B class and a D class, you will call B's constructor and then D's constructor, when you create an instance of D. For default constructors (i.e. with no arguments), you don't have to do anything. However, if B only implements a constructor which requires an argument, you need some way to pass this from D's constructor. To do this you use the base keyword similar to the way this is used in your example.

Brian Rasmussen
+1  A: 

This is a result (workaround) of lacking optional/default parameter support. You can find yourself in situations like:

MessageBox.Show(string)
...
MessageBox.Show(Window, string, string)
...
MessageBox.Show(Window, string, string, MessageBoxButton, MessageBoxImage, MessageBoxResult, MessageBoxOptions)

In these cases, usually the one with the most parameters contains an implementation and the other overloads just call that one with default parameters. One thing to note is that, when number of parameters grows to N, number of overloads might grow to N!.

Constructors are special functions, so you have to treat them as they deserve. An object can only be constructed once. Remember, in ordinary functions, you could call the implementation function as many times as you one. Here, you have to call the implementation constructor once and that is also the first thing to do. Constructor chaining syntax points out these requirements.

Lets get back to the original problem. Even though these cases are not very common, you can overcome this issue by defining a new type (here using C# 3.0 features) which will be used as the parameter:

public class Parameter
{
    public string P1 { get; set; }
    public int P2 { get; set; }
    public string P3 { get; set; }
    public double P4 { get; set; }
    ...
    public Parameter()
    {
        P1 = "p1";
        P2 = 2;
        P3 = "p3";
        P4 = 4.0;
        ...
    }
}
...
FunctionWithManyParametersCanNowBeCalledLike(new Parameter() { P2 = -2 });

Here we provided default parameters at the constructor. Is this a solution for many constructors? No.

C# 4.0 will include optional and named parameters feature. So we won't even need to define a new parameter type. You might think that feature as a syntactic sugar for this, however they differ. We will still need this syntax for base class constructor parameters.

orca