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.
- 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
- some code that uses parameterA and returns objectZ
- some code that uses parameterB and returns objectZ
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)
var objectZ = methodToExecute(null); //arguments here do not matter
Second, create the method that takes in parameter A or B and returns objectZ.
objectZ MethodToExecute(parameterA, parameterB)
if (paramaterA != null)
Finally, caller will pass in to this method the function to execute.
Method( (x) => methodToExecute(parameterA) )