Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

generics

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); 
like image 319
Greg Avatar asked Nov 22 '10 10:11

Greg


People also ask

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 TResult in C#?

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.

What will happen if a delegate has a non void return type?

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.

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.


2 Answers

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; 
like image 178
Marc Gravell Avatar answered Sep 21 '22 09:09

Marc Gravell


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

like image 32
Simone Avatar answered Sep 21 '22 09:09

Simone