Go from nullable to non-nullable after ReadFromJsonAsync
Asked Answered
A

1

5

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:

    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!;
Axseed answered 30/12, 2021 at 19:9 Comment(7)
@Ergis Is it safe to say that value returned by ReadFromJsonAsync is never null?Axseed
Why you need it non-nullable so badly? If you can't change the contract, then return a default value.Vanna
@Vanna body.Value does not work: 'T' does not contain a definition for 'Value' etcAxseed
@Vanna That's wrong, T is not a Nullable<T>. There is no .Value.Restrictive
I don't think it can actually ever return null and I'm not sure why it was written to return a nullable reference instead of just throwing. If you go with return body!; then if somehow it is null then eventually you'll just get a NRE the first time you try to deference it. The return body ?? throw new Exception() will on the other hand throw immediately which personally I think is better practice. Though I'd use something like InvalidOperationException with a message about the failure.Flosser
@Flosser what do you think about "return body!;" in this situation?Axseed
@Axseed I updated my comment. My rule of thumb is to use the null forgiveness operator as little as possible.Flosser
R
6

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.

Restrictive answered 30/12, 2021 at 19:56 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.