01 February 2018

C# – Passing method delegates as arguments.

I wanted to pass a method to execute to a helper method that created a response on API requests. If the method succeeded, it should return it's result; if an exception was thrown, it should return a 500 with the error. This is what I came up with:

/// <summary>
/// For methods that don't have a return value.
/// </summary>
protected HttpResponseMessage Respond(HttpRequestMessage request, Action method,
          HttpStatusCode errorStatusCode, string errorMessage)
{
    try
    {
        method();
        return request.CreateResponse(HttpStatusCode.OK);
    }
    catch
    {
        return request.CreateErrorResponse(errorStatusCode, errorMessage);
    }
}

/// <summary>
/// For methods that do have a return value.
/// </summary>
protected HttpResponseMessage Respond(HttpRequestMessage request, Func method,
          HttpStatusCode errorStatusCode, string errorMessage)
{
    try
    {
        return request.CreateResponse(HttpStatusCode.OK, method());
    }
    catch
    {
        return request.CreateErrorResponse(errorStatusCode, errorMessage);
    }
}

Now, I can respond to an API request in a single line:

return Respond(Request, () => Repo.Update(c), HttpStatusCode.InternalServerError, "Failed!");