V3068. Calling overrideable class member from constructor is dangerous.


The analyzer detected a potential error inside a class constructor - invoking an overridable method (virtual or abstract). The following example shows how such call can lead to an error:

abstract class Base
{
    protected Base()
    {
        Initialize();
    }

    protected virtual void Initialize()
    {
    ...
    }
}

class Derived : Base
{
    Logger _logger;
    public Derived(Logger logger)
    {
        _logger = logger;
    }

    protected override void Initialize()
    {
        _logger.Log("Initializing");
        base.Initialize();
    }
}

In this code, the constructor of abstract class Base contains a call to virtual method 'Initialize'. In the 'Derived' class, which is derived from the 'Base' class, we override the 'Initialize' method and utilize the '_logger' field in this overridden method. The '_logger' field itself is initialized in the 'Derived' class's constructor.

However, when creating an instance of the 'Derived' class, the constructor of the less derived type in the inheritance sequence will be executed first ('Base' class in our case). But when calling to the Initialize method from 'Base' constructor, we'll be executing the 'Initialize' method of the object created at runtime, i.e. the 'Derived' class. Note that when executing the 'Initialize' method, the '_logger' field will not be initialized yet, so creating an instance of the 'Derived' class in our example will cause a 'NullReferenceException'.

Therefore, invoking overridable methods in a constructor may result in executing methods of an object whose initialization is not complete yet.

To fix the analyzer warning, either mark the method you are calling (or the class that contains it) as 'sealed' or remove the 'virtual' keyword from its definition.

If you do want the program to behave as described above when initializing an object and you want to hide the analyzer's warning, mark the message as a false positive. For details about warning-suppression methods, see the documentation.


Bugs Found

Checked Projects
355
Collected Errors
13 303