A constructor calls a virtual or abstract method of its own class
What it finds
When a constructor calls a virtual method, an override in a subclass runs before the subclass's constructor has set its fields, so it sees them uninitialized. Sealed classes, and methods that are not virtual or abstract in the class itself, are left alone.
From the rule's source, virtual_call_in_constructor.rs.
abstract class Widget{ protected Widget() { Initialize();tx0 reports: the constructor calls the virtual method Initialize, which a subclass may override Layout();tx0 reports: the constructor calls the virtual method Layout, which a subclass may override Measure(); } protected abstract void Initialize(); protected virtual void Layout() { } private void Measure() { }} sealed class Label{ public Label() { Draw(); } public void Draw() { }} Turn it on, off or suppress it
The rule runs from the recommended tier up. To turn it on in a lower tier, give it a level in tx0.toml:
[rules]
"tx0/csharp:virtual-call-in-constructor" = "warning"To keep one finding, suppress it with a reason. tx0 suppress ID --reason "..." writes the comment on the line before the code:
// tx0: ignore[tx0/csharp:virtual-call-in-constructor] reason="..."tx0 explain tx0/csharp:virtual-call-in-constructor shows the same in the terminal. Found a false positive? Report it.