Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Execute Method Before and After Code Block

Tags:

c#

.net

How could I wrap some code in brackets to do the following?

MyCustomStatement(args){
// code goes here
}

So that before the code in the brackets executes, it'll call a method and when the code in the brackets finishes executing it will call another method. Is there such a thing? I know it seems redundant to do this when I can simply call the methods before and after the code and all, but I simply was curious. I don't know how to word this exactly because I'm new to programming.

Thanks!

like image 787
King John Avatar asked Jan 09 '23 14:01

King John


1 Answers

You can do this by storing the code in an abstract class that executes the "before" and "after" code for you when you call Run():

public abstract class Job
{
    protected virtual void Before()
    {
        // Executed before Run()
    }

    // Implement to execute code
    protected abstract void OnRun();

    public void Run()
    {
        Before();
        OnRun();
        After();
    }

    protected virtual void After()
    {
        // Executed after Run()
    }
}

public class CustomJob : Job
{
    protected override void OnRun()
    {
        // Your code
    }
}

And in the calling code:

new CustomJob().Run();

Of course then for every piece of custom code you'll have to create a new class, which may be less than desirable.

An easier way would be to use an Action:

public class BeforeAndAfterRunner
{
    protected virtual void Before()
    {
        // Executed before Run()
    }

    public void Run(Action actionToRun)
    {
        Before();
        actionToRun();
        After();
    }

    protected virtual void After()
    {
        // Executed after Run()
    }
}

Which you can call like this:

public void OneOfYourMethods()
{
    // your code
}

public void RunYourMethod()
{
    new BeforeAndAfterRunner().Run(OneOfYourMethods);
}
like image 109
CodeCaster Avatar answered Jan 21 '23 14:01

CodeCaster