Skip to content

Gendarme.Rules.BadPractice.ConstructorShouldNotCallVirtualMethodsRule(2.10)

Sebastien Pouliot edited this page Jan 22, 2011 · 2 revisions

ConstructorShouldNotCallVirtualMethodsRule

Assembly: Gendarme.Rules.BadPractice
Version: 2.10

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
Clone this wiki locally