Automatically making Base Constructors available in derived class?

No – you will need to implement the (appropriate) constructors in the derived class, as well.

The derived class only needs to use one of the base constructors – so the constructors required in it may be completely different than the base class. They will need to be implemented by hand, even if that’s just:

public class MyDerived : StoreBase
{
     public MyDerived(SomeObject sobj) : base(sobj) {}
     public MyDerived(OtherObject  oobj) : base(oobj) {}
}

Also:

(And yes, I know I could/should refactor this into a parameterless constructor and a protected virtual Initialize() method. but I still wonder if I can work with constructors and still avoid copy/paste)

Although I see this touted, I believe this is not always a good practice. In many cases, this is actually problematic, as you’re relying on the subclass to properly call Initialize if they override your protected virtual method. For example, if the subclass did this, it could potentially be very bad:

public class MyDerived : StoreBase
{
   // .. other stuff
   protected override void Initialize()
   {
       // Leave out, intentionally or accidentally, the following:
       // base.Initialize(); 
   }
}

I actually avoid this in most situations, and initialize in the constructors (or in a private, non-virtual initialize method). Not doing this breaks any guarantees you have that your initialization will always occur the way you intend.

Constructors and constructor chaining provide the same functionality, with much better guarantees.

Leave a Comment