Null propagation operator and Newtonsoft.Json 10.0.3 exception

I set "Newtonsoft.Json" version = "10.0.3"

and there are two methods:

    public static bool IsNull_yes(dynamic source)
    {
        if (source.x == null || source.x.y == null) return true;
        return false;
    }

    public static bool IsNull_exception(dynamic source)
    {
        if (source.x?.y == null) return true;
        return false;
    }

Then I have a program:

        var o = JObject.Parse(@"{  'x': null }");

        if (IsNull_yes(o) && IsNull_exception(o)) Console.WriteLine("OK");

        Console.ReadLine();
  • When the program calls the IsNull_yes method, then the result is true
  • When a program raises an IsNull_exception, the result is an exception: Microsoft.CSharp.RuntimeBinder.RuntimeBinderException: '' Newtonsoft.Json.Linq.JValue 'does not contain a definition for' y ''

Is this Newtonsoft.Json or another error?

+4
source share
2 answers

Short answer: source.x 'sort' null.

To see this, change the code as follows:

public static bool IsNull_exception(dynamic source)
{
    var h = source.x;  
    Console.WriteLine(object.ReferenceEquals(null, h));   // false
    Console.WriteLine(null == h);                         // false  
    Console.WriteLine(object.Equals(h, null));            // false
    Console.WriteLine(h == null);                         // true

    if (source.x?.y == null) return true;
    return false;
}

, false , true. , , dynamic, , object.Equals .. . @dbc .

, , ( null h == null).

, IsNull_yes -   - :

public static bool IsNull_yes(dynamic source)
{
    if (null == source.x || source.x.y == null) return true;
    return false;
}

(.. ).

+2

, , source.x?.y, json @"{ 'x': null }". , y , "x" , RuntimeBinderException.

-1

Source: https://habr.com/ru/post/1691021/


All Articles