Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling methods at beginning and end - is there a better way to do this in C#?

I have several methods that have the folling structure:

    public void doWhatever()
    {
     methodToPrepareEnvironment();
     // do something
     methodToResumeEnvironment();
    }

All my "doWhatever"-type methods call these prepare/resume methods and there is only 1 prepare and 1 resume method called by all these doWhatever methods. Is there a better way to achieve this without having to put a call to the prepare and resume methods at the beginning and end of all my doWhatever methods? I have the feeling I am missing something extremely basic here. Please note, the doWhatever methods cannot be combined, they each need to be independent and they each need to prepare the environment, do some tasks and then resume the environment.

Thank you.

like image 835
leoinlios Avatar asked Nov 17 '25 14:11

leoinlios


1 Answers

With strategic use of access modifiers you can ensure external calls are always preceded and followed by method calls with little repetition like so:

public void DoWhatever()
{
    DoAction(DoingWhatever);
}

private void DoingWhatever()
{
    // ...
}

private void DoAction(Action action)
{
    methodToPrepareEnvironment();

    action();

    methodToResumeEnvironment();
}

An Action is a delegate that represents a method with no return value.

like image 129
Phil Gan Avatar answered Nov 19 '25 02:11

Phil Gan