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!;
T
is not aNullable<T>
. There is no.Value
. – Restrictivereturn body!;
then if somehow it is null then eventually you'll just get a NRE the first time you try to deference it. Thereturn body ?? throw new Exception()
will on the other hand throw immediately which personally I think is better practice. Though I'd use something likeInvalidOperationException
with a message about the failure. – Flosser