I want to implement a function in the base class but I also want it to be overridden in the derived classes everytime. So it is more like "abstract function but with a body".
What am I looking for? Am I looking for the right thing?
I want to implement a function in the base class but I also want it to be overridden in the derived classes everytime. So it is more like "abstract function but with a body".
What am I looking for? Am I looking for the right thing?
If the base-class has something to say, but you want it overridden "every time", then I would have a pair of methods:
public void DoSomething() {
//things to do before
DoSomethingCore();
//things to do after
}
protected abstract void DoSomethingCore();
You're looking for a virtual
method (use this modifier to allow overriding the method), but you cannot force the user to overwrite it. Forcing this would not make sense if you have a body anyways, since one could just call base.YourMethod() and do nothing else, which does the same as not overriding the method in the first place.
public virtual YourMethod() {
// your base class code here
}
and then the overriding method in a different class:
public override YourMethod() {
// code to do before the base call
base.YourMethod();
// code to do after the base call
}
If your base class does something in the method, but you want to make sure that every subclass is forced to implement some part of the method, then you want the Template Method pattern, as described in Marc Gravell's answer.
There's no way to provide a default implementation in your base class and still force subclasses to provide their own implementation. You could however create an abstract base class and inherit from it to provide the default implementation, but make that concrete class sealed.
public abstract class FooBase {
public abstract void DoStuff();
}
public sealed class FooImpl : FooBase {
public override void DoStuff {
//default widget-munging code
}
}
Now any classes which inherit from FooBase have to implement DoStuff(), but you have a default implementation FooImpl from which subclasses may not inherit.
You might also prefer to delegate the responsibility for implementing the method to a separate class, which is passed to the base class in its constructor. That's called the Strategy pattern.
public sealed class Foo {
private IFooStrategy _strategy;
public Foo(IStrategy strategy) {
_strategy = strategy;
}
void DoStuff() {
_strategy.DoStuff();
}
public static IFooStrategy DefaultStrategy {
//return singleton instance of the default strategy
}
}
Now instead of subclassing Foo, you instead create new implementations of the IFooStrategy interface, and pass those to your Foo instance. So you could either do:
new Foo(Foo.DefaultStrategy);
or
new Foo(new DifferentStrategy());
Sounds like your base implementation will never be called. Why would you want to provide an implementation that nobody can get to (jumping through hoops not withstanding)