One could provide the desired runtime behavior if the base constructor accepts the ref
parameter and does something like (not thread safe):
private int myMagicCounter; public DerivedClass makeDerived(whatever) // A factory method { DerivedClass newThing; try { ... do whatever preparation newThing = new DerivedClass(ref myMagicCounter, whatever); } finally { ... do whatever cleanup } return newThing; } BaseClass(ref int magicCounter, whatever...) { if (magicCounter != myMagicCounter) throw new InvalidOperationException(); myMagicCounter++; if (magicCounter != myMagicCounter) throw new InvalidOperationException(); }
Note that to call the constructor of a derived class, it is impossible to gain control without executing the factory method or return control to its caller without clearing the factory method. However, there will be nothing to prevent the constructor of the derived class from passing its partially constructed instance to the external code, which can do whatever it likes with it for an arbitrary amount of time before returning control to the factory method.
source share