Search code examples
c#nullablereturn-type

Returning null T


I am having trouble returning null on this generic type T. I have tried marking it as Nullable, Nullable or T? without success...

This method is part of an abstract class and I need to make it as generic as possible so I can retrieve any type of object and use it from any derived class.

public T GetFromApi<T>(string apiRequest, string content)
{
    try
    {
        log.Debug("Requesting '" + apiRequest + "' from API with the following parameters: " + content);
        _httpClient.DefaultRequestHeaders.Accept.Clear();
        _httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
        _httpClient.DefaultRequestHeaders.Add("Authorization", string.Format("{0} {1}", _token.token_type, _token.access_token));

        var httpContent = new StringContent(content);
        HttpResponseMessage response = _httpClient.GetAsync(apiRequest).Result;

        if (response.IsSuccessStatusCode)
        {
            //Returns requested Object (T) from API
            log.Info("Returning requested object " + typeof(T).ToString());                    
            return response.Content.ReadAsAsync<T>().Result;
        }
        else
        {
            log.Error("Error accessing API.");
            return null;
        }
    }
    catch (Exception ex)
    {
        log.Fatal("Error accessing API.", ex);
        throw ex;
    }
}

The return null on the else statement gives me the error:

Cannot convert null to type parameter 'T'


Solution

  • Null may not be a viable value for T if the type passed in is a struct.

    You can instead return the default type for T which for a reference type is null:

    else
    {
        log.Error("Error accessing API.");
        return default(T);
    }
    

    As noted in the below comment, you can alternatively return null if you restrict T to class.

    public T GetFromApi<T>(string apiRequest, string content) where T : class
    ...
    else
    {
        log.Error("Error accessing API.");
        return null;
    }
    

    However, in the case where you DO need to potentially retrieve primitive types (bool, int, etc), you would no longer be able to consume this method.