I'm still quite new to C# (about 4months in) and I don't understand why this would be an issue.
#nullable enable
using System;
using System.Text.Json;
using System.Text.Json.Nodes;
public class Test{
public static void Main(){
var json = @"{""key"": ""value""}";
var node = JsonSerializer.Deserialize<JsonObject>(json);
if( node is null ){
return;
}
foreach( var property in node ){
var key = property.Key;
var val = (string) (property.Value?? "" ); // warning
Console.WriteLine($"{key}: {val}");
}
}
}
The line
var val = (string) (property.Value?? "" );
raises the warning
Converting null literal or possible null value to non-nullable type.
The C# documentation says specifically:
The null-coalescing operator ?? returns the value of its left-hand operand if it isn't null; otherwise, it evaluates the right-hand operand and returns its result. The ?? operator doesn't evaluate its right-hand operand if the left-hand operand evaluates to non-null.
This leads me to the conclusion, that the content of the parantheses property.Value?? ""
can never be null. Yet the warning seemingly suggests otherwise.
Is this a bug or am I misunderstanding something?