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

Generic Method

Possibly save 2 hours of your time: There are times when you want to refactor your method. This happens when you have duplicate code that acts on two similar objects.

Scenario:

  • You have ObjectA
  • You have ObjectB
  • You have Method1(ObjectA)
  • You have Method2(ObjectB)
  • Both Method1 and Method2 has exact code that operates on the similar Object.

Solution:

  • First, make ObjectA and ObjectB inherit same interface IObject

                class ObjectA : IObject

                class ObjectB : IObject

  • Then, change your Method1 and Method2 to

                 Method<T>(T object) where T : IObject

  • Third, refactor your method 1 and 2 so that your caller will just call this method with ObjectA or ObjectB as parameter

                 Method(objectAorB);