Search code examples
c#nullnullable

How to return T type or null in a method?


I need a method that returns a class with unspecified type or null.

I need this to handle API requests like, I'm requesting a file, let's say an image and an other file like a video and I need different types for that. If the image / video is not found, I want to return null.

I've already tried Nullables but I'm probably doing it the wrong way.

T? SendRequest<T?>(string pathOnServer)
{
    HttpResponseMessage response = SendTheRequest(pathOnServer);
    if(response.IsSuccessStatusCode)
        return JsonConvert.DeserializeObject<T>(response.Content.ReadAsStringAsync().Result);
    else
        return null;
}

Solution

  • It is simple.

    You just need to limit the method to what you say it should return.

    returns a class with unspecified type or null.

    That is T SendReuest<T> (string pathOnServer) where T : class

    As classes automatically can be nullable that is all that is needed. You just need to limit T to be a CLASS - not anything.