2

I'm still quite new to C# (about 4months in) and I don't understand why this would be an issue.

Run on DotNet Fiddle

#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?

infinitezero
  • 1,610
  • 3
  • 14
  • 29

1 Answers1

2

Depending on your goal you can use:

var val = property.Value?.ToString() ?? "" ;

Or

var val = property.Value?.ToJsonString() ?? "" ;

The problem with the warning seems to be that property.Value?? "" internally uses implicit conversion from string to JsonNode? and compiler does not understand that the resulting value is always not null (source code). I assume that it could be fixed in .NET 8 where it is marked with corresponding attribute:

[return: NotNullIfNotNull(nameof(value))]
public static implicit operator JsonNode?(string? value) => JsonValue.Create(value);
Guru Stron
  • 102,774
  • 10
  • 95
  • 132