4

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!

King John
  • 57
  • 2
  • 7

2 Answers2

7

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);
}
CodeCaster
  • 147,647
  • 23
  • 218
  • 272
  • Good answer. How can I call OneOfYourMethods method with parameters and how can I receive return value of the method. – suphero Apr 14 '15 at 12:07
  • @suphero see http://stackoverflow.com/questions/14738533/dispatch-invoke-new-action-with-a-parameter, http://stackoverflow.com/questions/4965508/how-can-i-pass-a-parameter-in-action – CodeCaster Apr 14 '15 at 12:37
3

To literally achieve what you want, you can use a delegate:

Action<Action> callWithWrap = f => {
    Console.WriteLine("Before stuff");
    f();
    Console.WriteLine("After stuff");
};

callWithWrap(() => {
    Console.WriteLine("This is stuff");
});

This requires adding "weird syntax" to your blocks and an understanding of how delegates and anonymous functions in C# work. More commonly, if you're doing this within a class, use the technique demonstrated in @CodeCaster's answer.

Jeroen Mostert
  • 27,176
  • 2
  • 52
  • 85