CA2214: Do not call overridable methods in constructors
Visual Studio 2012
|
TypeName |
DoNotCallOverridableMethodsInConstructors |
|
CheckId |
CA2214 |
|
Category |
Microsoft.Usage |
|
Breaking Change |
Non Breaking |
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.
using System; namespace UsageLibrary { public class BadlyConstructedType { protected string initialized = "No"; public BadlyConstructedType() { Console.WriteLine("Calling base ctor."); // Violates rule: DoNotCallOverridableMethodsInConstructors. DoSomething(); } // This will be overridden in the derived type. public virtual void DoSomething() { Console.WriteLine ("Base DoSomething"); } } public class DerivedType : BadlyConstructedType { public DerivedType () { Console.WriteLine("Calling derived ctor."); initialized = "Yes"; } public override void DoSomething() { Console.WriteLine("Derived DoSomething is called - initialized ? {0}", initialized); } } public class TestBadlyConstructedType { public static void Main() { DerivedType derivedInstance = new DerivedType(); } } }
This example produces the following output.
Calling base ctor. Derived DoSomething is called - initialized ? No Calling derived ctor.