-
Notifications
You must be signed in to change notification settings - Fork 4
Gendarme.Rules.BadPractice.ConstructorShouldNotCallVirtualMethodsRule(2.10)
Sebastien Pouliot edited this page Jan 22, 2011
·
2 revisions
Assembly: Gendarme.Rules.BadPractice
Version: 2.10
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.
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
- This rule is available since Gendarme 2.0
Note that this page was autogenerated (3/17/2011 9:31:58 PM) based on the xmldoc
comments inside the rules source code and cannot be edited from this wiki.
Please report any documentation errors, typos or suggestions to the
Gendarme Mailing List. Thanks!