C# translate Func method signature into a new Func method signature

Viewed 70

I have a method which receive this Func as parameter

Func<IContext, IReadOnlyCollection<T>> func

It happens that I need to log the duration of the execution of the Func above mentioned. I have already a function to log the duration of the execution, and this method has this signature:

T LogExecutionDuration<T>(Func<T> func);

My question is: There is a way to use the actual method, or do I need to create a new method to log it?

I would like to wrap the:

  Func<IContext, IReadOnlyCollection<T>> func 
  //into 
  T LogExecutionDuration<T>(Func<T> func);

  //In a way that the "Func<IContext, IReadOnlyCollection<T>> func" 
  //could be passed as parameter for LogExecutionDuration as Func<T> func

I think something similar is possible, because the following is possible:

public static T Foo<T>(Func<T> func){
    return func();
}

public static TResult Foo<T, TResult>(Func<T, TResult> func, T param){
    return func(param);
}

var foo1 = Foo(() => someObj.someMethod(someParam));
var foo2 = Foo(someObj.someMethod, someParam);

Maybe I misunderstood something, if is it the case, please explain me...

1 Answers

If I understood correctly, you want to curry a Func<T, R>.

You can write such a method:

public static Func<R> Curry<T, R>(Func<T, R> func, T arg) {
    return () => func(arg);
}

which is quite similar to your second Foo method, so you were on the right track.

And then do:

var curried = Curry(func, someIContext);
LogExecutionDuration(curried);

Note that you could also just do:

LogExecutionDuration(() => func(someIContext));
Related