C# way to write Func with void return

action, c#-4.0, delegates, func, refactoring

Solution

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.

Problem

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; } } ```

Original source