SharpAffair
SharpAffair

Reputation: 5478

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.

Upvotes: 3

Views: 2664

Answers (5)

John Fisher
John Fisher

Reputation: 22719

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);

Upvotes: 1

Jupaol
Jupaol

Reputation: 21365

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
   }
}

Upvotes: 2

Jon Senchyna
Jon Senchyna

Reputation: 8047

Assuming you need to use the two string parameters in the custom code, the following should get the job done. If you don't actually care about the results of the custom code, you can replace Func<string, string, TResult> with Action<string, string>. Additionally, if your custom code needs to process results from the common code above it, you can adjust the parameter types that your Func<> (or Action<>) takes in and then pass in the appropriate values.

void DoWork(string parameter1, string parameter2, Func<string, string, TResult> customCode) {
    //Common code 
    var customResult = customCode(parameter1, parameter2);
    //Common code 
}

Using Func<T, TResult>: http://msdn.microsoft.com/en-us/library/bb534960

Using Action<T>: http://msdn.microsoft.com/en-us/library/018hxwa8

Upvotes: 1

zmbq
zmbq

Reputation: 39013

If the custom code doesn't have to interact with the common code, it's easy:

void DoWork(..., Action custom)
{
    ... Common Code ...
    custom();
    ... Common Code ...
}

Upvotes: 1

Reed Copsey
Reed Copsey

Reputation: 564413

You would use delegates to handle this. It would likely look something like:

void DoWork(string parameter1, string parameter2, Action<string,string> customCode)
{
    // ... Common code
    customCode(parameter1, parameter2);
    // ... Common code
    customCode(parameter1, parameter2);
    // ... Common code
}

Upvotes: 1

Related Questions