'Warning CS8600 Converting null literal or possible null value to non-nullable type

However I try I get the following warning.

Severity Code Description Project File Line Suppression State Warning CS8600 Converting null literal or possible null value to non-nullable type.

The code is as follows.

HttpResponseMessage response = await _httpClient.PutAsync(url, requestContent);
string? userResponse = await response.Content.ReadAsStringAsync();
JsonSerializerOptions? options = new JsonSerializerOptions
{
  PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
};

//if (userResponse.Length > 0)
//{
  user = JsonSerializer.Deserialize<GetUserById>(userResponse, options);
//}

Looked at some posts like this and this, but could not figure out how to resolve.

Update.

I removed the if condition altogether, but still getting the warning.

Update 2

Added the null check as suggested. But still getting that warning.

Waring in C#



Solution 1:[1]

I believe it is warning you that userResponse is null and that it needs to be checked for a null state. If you do a null check that warning should go away.

Do this for you do the userResponse.Length Try this:

HttpResponseMessage response = await _httpClient.PutAsync(url, requestContent);
var userResponse = (string?)null;
userResponse = await response.Content.ReadAsStringAsync();
JsonSerializerOptions? options = new JsonSerializerOptions
{
  PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
};

if (userResponse != null)
{
  user = JsonSerializer.Deserialize<GetUserById>(userResponse, options);
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1