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.
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
}
}
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With