Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the best way to convert Action<T> to Func<T,Tres>?

Tags:

I have two functions in my class with this signatures,

public static TResult Execute<TResult>(Func<T, TResult> remoteCall); public static void Execute(Action<T> remoteCall) 

How can I pass the same delegate in the second method to the first one? Creating method with Delegate argument is not a way, because I am losing some exception information.

like image 685
Arsen Mkrtchyan Avatar asked Jun 03 '09 10:06

Arsen Mkrtchyan


People also ask

How do I return a func in C#?

The Types you are looking for are Action<> or Func<> . The generic parameters on both types determine the type signature of the method. If your method has no return value use Action . If it has a return value use Func whereby the last generic parameter is the return type.

What is func t TResult?

Func<T, TResult> defines a function that accepts one parameter (of type T) and returns an object (of type TResult).

What is the func in C#?

Func is a generic delegate included in the System namespace. It has zero or more input parameters and one out parameter. The last parameter is considered as an out parameter. The Func delegate that takes one input parameter and one out parameter is defined in the System namespace, as shown below: Signature: Func.

What is the difference between Func and Action delegate?

An Action type delegate is the same as Func delegate except that the Action delegate doesn't return a value. In other words, an Action delegate can be used with a method that has a void return type. It can contain minimum 1 and maximum of 16 input parameters and does not contain any output parameter.


1 Answers

Wrap it in a delegate of type Func<T, TResult> with a dummy return value, e.g.

public static void Execute(Action<T> remoteCall) {     Execute(t => { remoteCall(t); return true; }); } 
like image 57
Greg Beech Avatar answered Oct 22 '22 22:10

Greg Beech