Under what conditions am I supposed to make the :base()
and :this()
constructor calls following my constructor's parentheses (or even in other places in the code). When are these calls good practices and when are they mandatory?
: base(...)
If you omit the call to a base constructor it will call the default base constructor automatically.
It is mandatory to call a base constructor explicitly if there is no default constructor.
Even if there is a default constructor you may still wish to call a different constructor than the default constructor. In this case you may still wish to use base(foo, bar)
to call a different constructor than the base constructor.
I do not consider it to be a bad practice to omit base()
when you want to call to the base class default constructor, although if you like to be explicit I see no harm in including it. It is a matter of taste.
: this(...)
This syntax allows you to call one constructor with a different signature from another within the same class. It is never mandatory to do this, but can sometimes be useful.
An example of when it can be useful is for reusing common code in the constructors. For example in C# 3.5 or before you may want to simulate optional parameters on a constructor:
Foo(int x, int y)
{
this.x = x;
this.y = y;
}
Foo(int x) : this(x, 10) {} // y defaults to 10
With C# 4.0 optional parameters are now available which reduces the need for this approach.
An alternative way to reuse code in constructors is to factor it out into a static function which is called from each constructor that wishes to use it.