I want to do something like this:
public class MyClass {
public virtual void Foo() {
this.DoSomethingThatWouldBeFineInASubclassButAnOverrideWouldNotWantToUse();
}
}
Basically, I am doing some work here, and I want a default way of doing it, but if someone is going to override, they should likely NOT be using the default. It is so easy to put base.Foo() into an override without thinking about it; in fact my IDE does it automatically. I want to prevent that. Is it possible?
This is better solved with composition instead of inheritance. Perhaps, using the strategy pattern:
interface ISomeStrategy
{
void Do();
}
public class MyClass {
private readonly ISomeStrategy _strategy;
public MyClass() : this(null) {}
public MyClass(ISomeStrategy strategy)
{
// the default implementation and the user-defined implementation
// are mutually exclusive
_strategy = strategy ?? new DefaultStrategy();
}
public void Foo()
{
_strategy.Do();
}
//secret strategy
private class DefaultStrategy : ISomeStrategy
{
public void Do()
{
//secret implementation
}
}
}
Subclassing:
public class Derived : MyClass
{
public Derived() : base(new DerivedStrategy())
{
}
}
A bit more verbose, but effective.