Skip to content

Gendarme.Rules.BadPractice.ConstructorShouldNotCallVirtualMethodsRule(git)

Sebastien Pouliot edited this page Mar 2, 2011 · 1 revision

ConstructorShouldNotCallVirtualMethodsRule

Assembly: Gendarme.Rules.BadPractice
Version: git

Description

This rule warns the developer if any virtual methods are called in the constructor of a non-sealed type. The problem is that if a derived class overrides the method then that method will be called before the derived constructor has had a chance to run. This makes the code quite fragile.

Examples

Bad example:

class A {
    public A ()
    {
        this.DoSomething ();
    }
    protected virtual void DoSomething ()
    {
    }
}
class B : A {
    private int x;
    public B ()
    {
        x = 10;
    }
    protected override void DoSomething ()
    {
        Console.WriteLine (x);
    }
}
B b = new B (); // outputs 0 because B's constructor hasn't been called yet

Good example:

class A {
    public void Run ()
    {
        this.DoSomething ();
    }
    protected virtual void DoSomething ()
    {
    }
}
class B : A {
    private int x;
    public B ()
    {
        x = 10;
    }
    protected override void DoSomething ()
    {
        Console.WriteLine (x);
    }
}
B b = new B ();
b.Run (); // outputs 10 as intended

Notes

  • This rule is available since Gendarme 2.0

Source code

You can browse the latest source code of this rule on github.com

Clone this wiki locally