Under what conditions am I supposed to make the :base() and :this() constructor calls following my constructor\'s parentheses (or even in other pl
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);
}
}