Let's assume I have the following method:
private TResult CallWithSuccessHandler<TResult>(Func<TResult> func, System.Action onSuccess = null, System.Action onFailure = null)
{
try
{
var result = func();
if (onSuccess != null) onSuccess();
return result;
}
catch (Exception ex)
{
if (onFailure != null) onFailure();
throw;
}
}
I can invoke this method like this:
var simpleFunc = new Func<int>(() => { return 1; });
var result = CallWithSuccessHandler(simpleFunc, null, null);
This compiles without any problems in visual Studio and works fine.
However, what I can't figure out is how I can invoke the CallwithSucessHandler method with a "Func" that does not return anything. In other words, I need 'func' to return "void".
I attempted the following:
var voidFunc = new Func<void>(() => { return; });
CallWithSuccessHandler(voidFunc, null, null);
but Visual Studio refuses to compile and displays the following error message:
"Keyword 'void' cannot be used in this context"
Specifically, Visual Studio does not like "new Func < void >".
What would be the proper syntax for a Func that returns "nothing"?
Func<> defines a function that returns something. You can't tell it to return nothing as this doesn't make sense. Code that uses the delegate expects a value (i.e., your CallWithSuccessHandler, which has to return the result of the function) and void by definition cannot be a value.
You can return a dummy value, perhaps a boolean, but you have to return something.
As another answer pointed out, there is also Action which does not return a value. However, it is not compatible with a method that takes a Func<>, both in terms of type signature and in terms of semantics.
You could have two versions of CallWithSuccessHandler: one that takes a Func<> and one that takes an Action. The version for Action would have a return type of void.
A function with a return type of void doesn't return anything. If you want a delegate that refers to a method that doesn't return anything then you use Action rather than Func<TResult>.
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