Using void return types with new Func <T, TResult>

I use an anonymous delegate in my code calling this sample function:

public static int TestFunction(int a, int b) { return a + b; } 

The delegate is as follows:

 var del = new Func<int, int, int>(TestFunction); 

My question is: how do you specify the void return type for TResult ? The following does not work:

 public static void OtherFunction(int a, string b) { ... } var del = new Func<int, string, void>(OtherFunction); 
+24
generics c #
Nov 22 '10 at 10:18
source share
4 answers

If there is no return type, you want Action<int,string> :

 var del = new Action<int, string>(OtherFunction); 

or simply:

 Action<int, string> del = OtherFunction; 
+41
Nov 22 '10 at 10:19
source share

You must use Action <T> if you want to return void.

+6
Nov 22 '10 at 10:21
source share

You need an Action <T> if you do not want to return something

+3
Nov 22 '10 at 10:24
source share

Use action instead of Func if you don't need any return value

  public void InvokeService<T>(Binding binding, string endpointAddress, Action<T> invokeHandler) where T : class { T channel = FactoryManager.CreateChannel<T>(binding, endpointAddress); ICommunicationObject communicationObject = (ICommunicationObject)channel; try { invokeHandler(channel); } finally { try { if (communicationObject.State != CommunicationState.Faulted) { communicationObject.Close(); } } catch { communicationObject.Abort(); } } } 
0
Nov 27 '15 at 10:00
source share



All Articles