Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass code to a method as an argument

I have a list of methods that do pretty much the same thing, except a few differences:

void DoWork(string parameter1, string parameter2)

{

//Common code
...

//Custom code
...

//Common code
...

}

I want to streamline the solution with reusing the common code by passing custom code from another method.

I assume I have to use an action with parameters to accomplish this, but can't figure out how.

like image 934
SharpAffair Avatar asked Jan 22 '26 00:01

SharpAffair


2 Answers

You could try the Template method pattern

Which basically states soemthing like this

abstract class Parent
{
   public virtual void DoWork(...common arguments...)
   {
      // ...common flow
      this.CustomWork();
      // ...more common flow
   }

   // the Customwork method must be overridden
   protected abstract void CustomWork();
}

In a child class

class Child : Parent
{
   protected override void CustomWork()
   {
      // do you specialized work
   }
}
like image 139
Jupaol Avatar answered Jan 23 '26 12:01

Jupaol


The other answers are great, but you may need to return something from the custom code, so you would need to use Func instead.

void Something(int p1, int p2, Func<string, int> fn)
{
   var num = p1 + p2 + fn("whatever");
   // . . .
}

Call it like this:

Something(1,2, x => { ...; return 1; });

Or:

int MyFunc(string x)
{
    return 1;
}

Something(1,2 MyFunc);
like image 45
John Fisher Avatar answered Jan 23 '26 14:01

John Fisher