Pass Function as parameter to Method

Possibly save 3 hours of your time: There are times when you would like to refactor code but realize a piece of that code is different based on the caller. The caller may also used different parameters, but return the same object.

Scenario:

  • Caller1 calls Method1 with parameterA and returns objectZ
  • Caller2 calls Method2 with parameterB and returns objectZ
  • Method1 and Method2 has same code except for the piece of code that returns objectZ

Method1:

  • code…
  • some code that uses parameterA and returns objectZ
  • code…

Method2:

  • code…
  • some code that uses parameterB and returns objectZ
  • code…

Solution:

You can use Func delegate as parameter. Func can return an object. The example below shows the use of this Func delegate as parameter.

You can also use Action as paramater, but Action does not return an object.

First, refactor the Method1 and Method2 that takes in a Func delegate with different parameters.

Method(Func<string, objectZ> methodToExecute)

{

same code…

var objectZ = methodToExecute(null); //arguments here do not matter

same code…

}

Second, create the method that takes in parameter A or B and returns objectZ.

         objectZ MethodToExecute(parameterA, parameterB)

{

if (paramaterA != null)

return ObjectZ(parameterA);

return ObjectZ(parameterB);

}

Finally, caller will pass in to this method the function to execute.

Method( (x) => methodToExecute(parameterA) )

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s