Mark Levison

Musings on No Touch Deployment, .NET development and photography

<September 2008>
SuMoTuWeThFrSa
31123456
78910111213
14151617181920
21222324252627
2829301234
567891011


Navigation

Other

Blogroll

Subscriptions

Post Categories



Thursday, April 22, 2004 - Posts

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 Thursday, April 22, 2004 1:45 PM by mlevison with 2 Comments




Powered by Dot Net Junkies, by Telligent Systems