views:

102

answers:

3

Can I somehow force a derived class to always call the overridden methods base?

public class BaseClass
{
    public virtual void Update()
    {
        if(condition)
        {
            throw new Exception("..."); // Prevent derived method to be called
        }
    }
}

And then in a derived class :

public override void Update()
{
    base.Update(); // Forced call

    // Do any work
}

I've searched and found a suggestion to use a non-virtual Update() but also a protected virtual UpdateEx(). It just doesn't feel very neat, isn't there any better way?

I hope you get the question and I am sorry for any bad English.

+1  A: 

I think that the suggestion which you found is good.

The only base class method which you can't avoid calling from the subclass in base class constructor.

ChrisW
+1  A: 

I think having a non-virtual base member that calls a virtual "hook" that can be extended is the most common solution for this kind of problem.

Depending on your use case, you might want to use an event instead, but the usual pattern for implementing an event is to have a virtual OnEvent method that subclasses can override instead of adding an event handler, so in your example case it boils down to the same thing.

Daniel Pryden
+10  A: 

Use the template method pattern - don't override the base method which needs to do some work, override one specific bit, which can either be abstract or a no-op in the base class. (The decision about whether to make it a no-op or abstract is usually fairly obvious - does the base class make sense on its own, as a concrete class?)

It sounds like this is basically the pattern you've found with UpdateEx - although it's usually UpdateImpl or something similar in my experience. There's nothing wrong with this as a pattern, in my view - it avoids any idea of forcing all derived classes to write the same code to call the base method.

Jon Skeet
While I agree that the template method pattern is often preferable, it should be noted that the BCL makes heavy use of the "overrides must call the base class method" (anti?)pattern. This is particularly true of Windows Forms classes.
hemp