Jatin Sanghvi
Jatin Sanghvi

Reputation: 2243

Return a boolean from generic method for boolean return type

I have a generic method SendHttpRequest<TRequest, TResponse> that takes in a request-type and a response-type as its generic parameter inputs. The response-type can be either a boolean or a class representing the response.

My task is to return true if HTTP request made inside the method is successful and TResponse is a bool. If instead TResponse is of different type, I need to unserialize the response content into TResponse object. Returning true generates compile-time error. Is there a way to have a single method that supports both boolean and non-boolean return types?

private async Task<TResponse> SendHttpRequest<TRequest, TResponse>(TRequest request)
{
    using (var client = new HttpClient())
    {
        client.BaseAddress = "http://example.com/";

        var response = await client.PostAsJsonAsync("api_path", request).ConfigureAwait(false);

        if (!response.IsSuccessStatusCode)
        {
            throw new MyException(response);
        }

        if (typeof (TResponse) == typeof (bool))
        {
            return true; // Generates compile-time error
        }
        else
        {
            var content = await response.Content.ReadAsStringAsync().ConfigureAwait(false);
            return JsonConvert.DeserializeObject<TResponse>(content);
        }
    }
}

Upvotes: 3

Views: 3038

Answers (1)

Evk
Evk

Reputation: 101473

I suppose you already understand that it's a bad design, but if you really want to make it exactly like this, you can do it:

private async Task<TResponse> SendHttpRequest<TRequest, TResponse>(TRequest request)
{
    using (var client = new HttpClient())
    {
        client.BaseAddress = "http://example.com/";

        var response = await client.PostAsJsonAsync("api_path", request).ConfigureAwait(false);

        if (!response.IsSuccessStatusCode)
        {
            throw new MyException(response);
        }

        if (typeof (TResponse) == typeof (bool))
        {
            return (TResponse)(object)true;
        }
        else
        {
            var content = await response.Content.ReadAsStringAsync().ConfigureAwait(false);
            return JsonConvert.DeserializeObject<TResponse>(content);
        }
    }
} 

Upvotes: 6

Related Questions