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.