ReSharper 2017.3 Help

Code Inspection: Virtual member call in constructor

As Eric Lippert explains in this post, base type initializers run after the derived type initializers but the constructors are executed in the opposite order, i.e. constructors of derived types are called after constructors of base types. On the other hand, calls to virtual methods are always executed on the most derived type.

This means that if you call a virtual member from the constructor in a base type, each override of this virtual member in a derived type will be executed before the constructor of the derived type is called.

As you can imagine, if the override in the derived type uses its members, this can lead to confusion and errors.

It is often seen, that a virtual call in the constructor is meant to allow the derived type to set up some aspect of the base type. Such virtual method, in fact, should be a pure function that returns some value and doesn't depend on the state of the derived type. If this is the case, make such function static (since it is pure) and pass its return value to the base type as a parameter to protected constructor.

Last modified: 15 March 2018

See Also