Run a method before all methods of a class

You can't do this automatically in C# - you should probably be looking at AOP, e.g. with PostSharp.


I know it won't answer the question directly. But it's a good approach to use a decorator pattern to solve this problem to make your implementation stay clean.

Create an interface

public interface IMagic
{


    public void Method1()
    {
    }


    public void Method2()
    {
    }
}

Create implementation

public class Magic : IMagic
{

    public void Method1()
    {
    }


    public void Method2()
    {
    }
}

Create Decorator

public class MagicDecorator : IMagic
{
   private IMagic _magic;
   public MagicDecorator(IMagic magic)
   {
       _magic = magic;
   }

   private void BaseMethod()
   {
       // do something important
   }

    public void Method1()
    {
         BaseMethod();
         _magic.Method1();
    }


    public void Method2()
    {
        BaseMethod();
        _magic.Method2();
    }
}

Usage

var magic = new MagicDecorator(new Magic());
magic.Method1();
magic.Method2();

There is an alternate solution for this, make Magic a singleton and put your code on the getter of the static instance. That's what i did.

public class Magic{

private static Magic magic;
public static Magic Instance{
  get
    {
   BaseMethod();
    return magic;
    }
}

public void BaseMethod(){
}

//runs BaseMethod before being executed
public void Method1(){
}

//runs BaseMethod before being executed
public void Method2(){
}
}

Tags:

C#

Reflection