Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Go from nullable to non-nullable after ReadFromJsonAsync

ReadFromJsonAsync method returns nullable T. Here is a code sample:

private async Task<T> Get<T>(Uri url, CancellationToken cancellationToken)
{
    using HttpResponseMessage response = await _httpClient.GetAsync(url, cancellationToken);

    T? body = await response.Content.ReadFromJsonAsync<T>(cancellationToken: cancellationToken);

    return body ?? throw new Exception();
}

I want my method to return non-nullable value.

I am wondering when ReadFromJsonAsync will return null. No matter how I have tried I was still getting instance of T with all properties equal null. So I hoped that it would be safe to write code like this:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

    return (T)body;

But now I am getting a warning Converting null literal or possible null value to non-nullable type.

What about this, is it a good idea:

    return body!;

>Solution :

ReadFromJsonAsync is a utility method that gets the response’s content stream and then passes that to JsonSerializer.DeserializeAsync.

DeserializeAsync is defined as returning a nullable value, because it might return null. It will do so in the case where you attempt to deserialize a null JSON value.

If you don’t expect those, then you can use ! to just ignore the warning. But the safest way would be to indeed check for null and either throw an exception or return a fallback balue.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading