C# - Complete return from base method

Talib picture Talib · May 28, 2012 · Viewed 7.3k times · Source

I have a virtual base method void Action() that is overridden in a derived class.

The first step in Action is to call base.Action(). If a situation occurs in the base method I do not want the rest of the derived method to be processed.

I want to know is there a keyword or design pattern that will allow me to exit the derived method from the base method.

Currently I am looking at changing the void to bool and using that as a flow control, but I was wondering if there are any other design patterns I might be able to use.

Answer

Jon Skeet picture Jon Skeet · May 28, 2012

Is this an error "situation"? If so, just make it throw an exception, and don't catch the exception within the override.

If it's not an error situation, then using the return type does sound like a way forward, but it may not be suitable for your context - we don't really know what you're trying to achieve.

Another option is to use the template method pattern:

public abstract class FooBase
{
    public void DoSomething()
    {
        DoUnconditionalActions();
        if (someCondition)
        {
            DoConditionalAction();
        }
    }

    protected abstract void DoConditionalAction();
}

If you don't want to make the base class abstract, you could make it a protected virtual method which does nothing in the base class and is overridden in the derived class where appropriate. Note that DoSomething is not virtual here.

If none of these options sounds appropriate, you'll need to provide us more concrete information about what you're trying to achieve.