Search code examples
c#ooplanguage-agnostic

Is it possible a base class gets informed when a method in derived class is called?


Consider the following little design:

public class Parent
{
  public event EventHandler ParentWentOut;
  public virtual void GoToWork()
  {
     ParentWentOut();
  }
}

public class Mother : Parent
{
   public override void GoToWork()
   {
     // Do some stuff here
     base.GoToWork(); // <- I don't want to write this in any derived class. 
                      //    I want base class's method to be automatically called.
   }
}

Is there any mechanism to make Parent.GoToWork method implicitly and automatically be called whenever this method finishes in overridden version of the descendants (here Mother class) ?

If there is any other language than C# able to do so, I'll be very thankful to know.


Solution

  • You can try to implement something like this

    public class Parent
    {
       public event EventHandler ParentWentOut;
       public void GoToWork()
       {
         BeforeParentWentOut();
         ParentWentOut();
         AfterParentWentOut();         
       }
    
       protected virtual void BeforeParentWentOut()
       {
          // Dont do anything, you can even make it abstract if it suits you
       }
    
       protected virtual void AfterParentWentOut()
       {
          // Dont do anything, you can even make it abstract if it suits you
       }
    }
    
    
    
    public class Mother : Parent
    {
       protected override void BeforeParentWentOut()
       {
          // Do some stuff here
       }
    }
    

    Also you can subscribe to your own event on the Mother class and react to that.

    EDIT: update for protected, added before/after methods to handle when to add code to the parent implementation