Automatically call base method prior the derived one

I have a base class:

abstract class ClassPlugin
{

    public ClassPlugin(eGuiType _guyType)
    {
            GuiType = _guyType;
    }

    public eGuiType GuiType;

    protected void Notify(bool b)
    {
        ...
    }

    protected virtual void RaiseAction()
    {
        Notify(false);
    }
}

and then I have some derived classes:

class ClassStartWF : ClassPlugin
{

    public ClassStartWF(eGuiType _guyType) : base(_guyType) { }

    public event delegate_NoPar OnStartWorkFlow_Ok;

    public void Action()
    {
        Notify(true);
        RaiseAction(eEventType.OK);
    }

    public new void RaiseAction(eEventType eventType)
    {
            base.RaiseAction();<--------------------

            if (OnStartWorkFlow_Ok == null)
                MessageBox.Show("Event OnStartWorkFlow_Ok null");
            else
                OnStartWorkFlow_Ok();
        }
    }
}

now in the raise action I have to call before the base.RaiseAction() method but that can be forgotten. Is there a way to automatically call the base method (and do some actions there ) before the derived method is called?

Jon Skeet
people
quotationmark

The standard solution to this is to use the template method pattern:

public abstract class Base
{
    // Note: this is *not* virtual.
    public void SomeMethod()
    {
        // Do some work here
        SomeMethodImpl();
        // Do some work here
    }

    protected abstract void SomeMethodImpl();
}

Then your derived class just overrides SomeMethodImpl. Executing SomeMethod will always execute the "pre-work", then the custom behaviour, then the "post-work".

(In this case it's not clear how you want your Notify/RaiseEvent methods to interact, but you should be able to adapt the example above appropriately.)

people

See more on this question at Stackoverflow