Can I inherit constructors?

You don't need to create loads of constructors, all with the same code; you create only one, but have the derived classes call the base constructor:

public class Base
{
    public Base(Parameter p)
    {
        Init(p)
    }

    void Init(Parameter p)
    {
        // common initialisation code
    }
}

public class Derived : Base
{
    public Derived(Parameter p) : base(p)
    {
 
    }
}

The only way to not repeat the base.Init call is to instead call the base constructor

class Base
{
  public Base(Parameter p)
  {
    this.Init(p)
  }

  private void Init(Parameter p)
  {
      ...
  }
}

class Inherited : Base
{
   public Inherited(Parameter p)
     : base(p)
   {
      // other constructor logic, but Init is already called.
   }
}

Change the init function so it is the constructor for the base class, and then call it from the inherited objects like this:

public InheritedObject(Parameter p) : base(p)
{
}

The base constructor will be invoked before any code in the constructor itself runs.


You can't inherit constructors but you can call them from your derived children's constructors. If you make the base classes default constructor private it will force you to select a base constructor every time you create a derived class.

class A
{
    protected A(int x)
    {

    }
}
class B : A
{
    B(int x)
        : base(x)
    {

    }
}

Tags:

C#

Dry