Mark Levison

Musings on No Touch Deployment, .NET development and photography

<November 2008>
SuMoTuWeThFrSa
2627282930311
2345678
9101112131415
16171819202122
23242526272829
30123456


Navigation

Other

Blogroll

Subscriptions

Post Categories



FxCop rule "Constructors should not call virtual methods defined by the class"

FxCop defines the rule ConstructorsShouldNotCallBaseClassVirtualMethods:

"When a virtual method is called, the actual type that executes the method is not selected until run time. When a constructor calls a virtual method, there is a chance that the constructor for the instance that invokes the method has not executed."

This bans the useful idiom:

public abstract class foo {
    private readonly SomeType some;

    protected foo() {
        some = CreateSomeType();
       new Other(some)

    }

    protected abstract SomeType CreateSomeType();
}

public class fooBar : foo {
    protected override SomeType CreateSomeType() {
        return new SomeType();
    }
}
public class fooPrime : foo {
    protected override SomeType CreateSomeType() {
        return new OtherType();
    }
}

Is there a better idiom that will force a derived class to perform initialization during construction?

Obviously I can exclude the violation, but I like to see if there is better solution to FxCop violations before I just exclude them.

Update: When I wrote this yesterday, I forgot to make the member variable some readonly.  That's actually entire point of this pattern.  It allows us to create immutable objects whose contents differ by derived class.

posted on Thursday, April 22, 2004 1:45 PM by mlevison





Powered by Dot Net Junkies, by Telligent Systems