Make sure base method gets called in C#

Matteus Hemström picture Matteus Hemström · May 31, 2010 · Viewed 10.1k times · Source

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.

Answer

Jon Skeet picture Jon Skeet · May 31, 2010

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.