Search code examples
c#classmethodspartial-methods

Calling a method when another method is called


This might be a stupid question, but here goes.

I have the following problem:

public class MyBaseClass
{
    public void SomethingAwesome()
    {
        //Awesome stuff happens here, but only when the Something() method
        //is called in the other classes.
    }
}

public class SomeClass : MyBaseClass
{
    public void Something()
    {
        //Something happens here
    }
}

public class SomeOtherClass : MyBaseClass
{
    public void Something()
    {
        //Something else happens here
    }
}

MyBaseClass has a method which needs to be called when the Something() method is called in the class that inherits from it.

The idea behind this is that I need to log when this method is called for lots of boring corporate reasons. I would rather have a base class which automatically audits when a method is called, rather than having the developer call the method himself/herself.

Can something like this be achieved? If so, how?

I've considered partial methods, but that would require classes with the same name, which isn't possible in this scenario.


Solution

  • It sounds like you want the template method pattern:

    public abstract class MyBaseClass
    {
        public void Something()
        {
            // Code from SomethingAwesome here, or keep SomethingAwesome
            // separate and call it from here
            SomethingImpl();
        }
    
        protected abstract void SomethingImpl();
    }
    
    public class SomeClass : MyBaseClass
    {
        protected override SomethingImpl()
        {
            // Something happens here
        }
    }
    

    That's assuming you're happy for MyBaseClass to have a public Something method, of course - if it doesn't declare Something (in some way) then the two Something methods in the derived classes are unrelated.