C# way to write Func with void return

CaffGeek picture CaffGeek · Jun 4, 2012 · Viewed 7.3k times · Source

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

Answer

Reed Copsey picture Reed Copsey · Jun 4, 2012

You could use your second, Func<T> version, to implement the Action method by just wrapping the Action in a lambda. This eliminates some of the duplicated code.

private static void TryCatch(Action action)
{
    Func<object> fun => 
       {
           action();
           return null;
       };
    TryCatch(fun);
}

That being said, there is extra overhead involved in doing this, so personally, I'd probably leave it the way you currently have it implemented (especially given how short and simple your original version happens to be in this case).