ReSharper 2016.1 Help

Code Inspection: Virtual member call in constructor

What's the harm in calling a virtual method in a constructor? Well, the problem is that virtual calls always act on the most derived type. This means that, if you make a virtual call in a constructor, and the type you're on is not the most derived type, you'll end up calling it on a class whose constructor has not been run. As you can imagine, this can, in certain situations, lead to confusion and errors.

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

See Also

Last modified: 19 August 2016