: 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.
First off, when they're mandatory.
When a class Derived is derived from a class Base, and Base does not have a default (parameterless) constructor, Derived must call base() explicitly with parameters.
public class Base {
public Base(int i) { }
}
public class Derived : Base {
// public Derived() { } wouldn't work - what should be given for i?
public Derived() : base(7) { }
public Derived(int i) : base(i) { }
}
When is it good practice? Whenever you want to call a different constructor.
Suppose you add, in my previous example, content to the constructors in Derived.
public class Derived : Base {
// public Derived() { } wouldn't work - what should be given for i?
public Derived() : base(7) {
Console.WriteLine("The value is " + 7);
}
public Derived(int i) : base(i) {
Console.WriteLine("The value is " + i);
}
}
You notice the duplication here? It's simpler to call the this() constructor.
public class Derived : Base {
// public Derived() { } wouldn't work - what should be given for i?
public Derived() : this(7) { }
public Derived(int i) : base(i) {
Console.WriteLine("The value is " + i);
}
}