Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Keyword 'void' cannot be used in this context when trying to declare a Func<void>

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"?

like image 863
desautelsj Avatar asked Jan 29 '26 11:01

desautelsj


2 Answers

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.

like image 119
siride Avatar answered Jan 31 '26 01:01

siride


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>.

like image 34
jmcilhinney Avatar answered Jan 31 '26 01:01

jmcilhinney