Search code examples
c#inheritancemultiple-constructorsinherited-constructors

How to declare constructors in base classes so that sub-classes can use them without declaring them?


I want a subclass to use its parent's constructors. But it seems I always need to define them again in the subclass in order for that to work, like so:

public SubClass(int x, int y) : base (x, y) {
    //no code here
}

So I'm wondering if I'm not declaring the constructor properly in the parent class, or is there no direct constructor inheritance at all?


Solution

  • You are not doing anything wrong.

    In C#, instance constructors do not get inherited, so declaring them on the inheriting type and chaining to the base constructor is the right way about it.

    From the spec §1.6.7.1:

    Unlike other members, instance constructors are not inherited, and a class has no instance constructors other than those actually declared in the class. If no instance constructor is supplied for a class, then an empty one with no parameters is automatically provided.