CA2214: Do not call overridable methods in constructors

 

The new home for Visual Studio documentation is Visual Studio 2017 Documentation on docs.microsoft.com.

The latest version of this topic can be found at CA2214: Do not call overridable methods in constructors.

TypeName|DoNotCallOverridableMethodsInConstructors|
|CheckId|CA2214|
|Category|Microsoft.Usage|
|Breaking Change|Non Breaking|

The constructor of an unsealed type calls a virtual method defined in its class.

When a virtual method is called, the actual type that executes the method is not selected until run time. When a constructor calls a virtual method, it is possible that the constructor for the instance that invokes the method has not executed.

To fix a violation of this rule, do not call a type's virtual methods from within the type's constructors.

Do not suppress a warning from this rule. The constructor should be redesigned to eliminate the call to the virtual method.

The following example demonstrates the effect of violating this rule. The test application creates an instance of DerivedType, which causes its base class (BadlyConstructedType) constructor to execute. BadlyConstructedType's constructor incorrectly calls the virtual method DoSomething. As the output shows, DerivedType.DoSomething() executes, and does so before DerivedType's constructor executes.

No code example is currently available or this language may not be supported.

This example produces the following output.

Calling base ctor.
Derived DoSomething is called - initialized ? No
Calling derived ctor.

Show: