Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Call a parent method before(or after) any child method

Tags:

c#

inheritance

Most likely I'll get negative answer here, but I'd like to ask my question.

Is there a way in C# to call the parent method before (or after) ANY child class method.

public class Base
{
    protected static void ThisWillBeCalledBeforeAnyMethodInChild()
    {
        //do something, e.g. log
    }

    protected static void ThisWillBeCalledAFTERAnyMethodInChild()
    {
        //do something, e.g. log
    }
}

public class SomeClass : Base
{
    public static void SomeMethod1()
    {
        //Do something
    }

    public static void SomeMethod2()
    {
        //Do something
    }
}

So, I want to method ThisWillBeCalledBeforeAnyMethodInChild from Base class to run before SomeMethod1 or SomeMethod2 in SomeClass. Similar with after method.

Is there any way to do it without calling methods with reflection?

like image 865
angrybambr Avatar asked Feb 19 '19 15:02

angrybambr


1 Answers

So, aside from in your child method calling base.MethodNameYouWantToCall() before or after, you could take a different approach.

This is just an idea, and might not be what you're trying to achieve, but if I needed every child class to call parent functions before and after something I might do this:

class Parent 
{ 
   protected void Before() { /* does things */ }
   protected void After() { /* does things */ }
   abstract void OtherCode();

   public void PubliclyExposedMethod {
        Before();
        OtherCode();
        After();'
}
class Child : Parent {
      OtherCode { Console.Write("Hello world"); }
}

In the above, the method you define in the child will be ran after the before method, and before the after. I think this is cleaner because it reduces the number of times you need to write base.()

like image 184
Jlalonde Avatar answered Sep 25 '22 13:09

Jlalonde