Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# way to write Func with void return

I have the following two functions, that are nearly identical, the only difference is that one uses func, the other action. And I'd like to combine them into one function if it is possible.

    private static void TryCatch(Action action)
    {
        try
        {
            action();
        }
        catch (Exception x)
        {
            Emailer.LogError(x);
            throw;
        }
    }

    private static TResult TryCatch<TResult>(Func<TResult> func)
    {
        try
        {
            return func();
        }
        catch (Exception x)
        {
            Emailer.LogError(x);
            throw;
        }
    }
like image 745
CaffGeek Avatar asked Jun 04 '12 16:06

CaffGeek


1 Answers

Combining these two into one function in C# really isn't possible. The void in C#, and CLR, simply isn't a type and hence has different return semantics than a non-void function. The only way to properly implement such a pattern is to provide an overload for void and non-void delegates

The CLR limitation doesn't mean it's impossible to do in every CLR language. It's just impossible in languages which use void to represent a function which returns no values. This pattern is very doable in F# because it uses Unit instead of void for methods which fail to return a value.

like image 191
JaredPar Avatar answered Sep 26 '22 13:09

JaredPar