I'm using an anonymous delegate in my code calling this example function:
public static int TestFunction(int a, int b) { return a + b; }
The delegate looks like this:
var del = new Func<int, int, int>(TestFunction);
My question is: how do you specify a void
return type for TResult
? The following doesn't work:
public static void OtherFunction(int a, string b) { ... } var del = new Func<int, string, void>(OtherFunction);
Func<T, TResult> defines a function that accepts one parameter (of type T) and returns an object (of type TResult).
TResult. The type of the return value of the method that this delegate encapsulates. This type parameter is covariant. That is, you can use either the type you specified or any type that is more derived. For more information about covariance and contravariance, see Covariance and Contravariance in Generics.
When the return type is not void as above in my case it is int. Methods with Int return types are added to the delegate instance and will be executed as per the addition sequence but the variable that is holding the return type value will have the value return from the method that is executed at the end.
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.
If there is no return type, you want Action<int,string>
:
var del = new Action<int, string>(OtherFunction);
or just:
Action<int, string> del = OtherFunction;
You have to use Action< T > if you want to return void.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With