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;
}
}
Combining these two into one function in C# really isn’t possible. The
voidin 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 delegatesThe CLR limitation doesn’t mean it’s impossible to do in every CLR language. It’s just impossible in languages which use
voidto represent a function which returns no values. This pattern is very doable in F# because it usesUnitinstead ofvoidfor methods which fail to return a value.