C# inheritance and default constructors

Now, on creating a new instance of class B, which constructor of class A is automatically called before invoking the class B constructor?

The code will fail to compile, basically. Each constructor has to chain to another constructor, either implicitly or explicitly. The constructor it chains to can be in the same class (with this) or the base class (with base).

A constructor like this:

public B() {}

is implicitly:

public B() : base() {}

… and if you don’t specify a constructor at all, it will be implicitly added in the same way – but it still has to have something to call. So for example, your scenario:

public class A
{
    public A(int x) {}
}

public class B : A {}

leads to a compiler error of:

error CS7036: There is no argument given that corresponds to the required formal parameter 'x' of 'A.A(int)'

However, you can specify a different constructor call explicitly, e.g.

public B() : base(10) {} // Chain to base class constructor

or

public B() : this(10) {} // Chain to same class constructor, assuming one exists

Leave a Comment