I have installed "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 program:
var o = JObject.Parse(@"{ 'x': null }");
if (IsNull_yes(o) && IsNull_exception(o)) Console.WriteLine("OK");
Console.ReadLine();
Is it Newtonsoft.Json or other bug?
The short answer is that source.x
is 'sort of' null.
To see this, change the code as following:
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;
}
You will note that false
is written three times, then true
. As such, the equality comparison used by dynamic
is not the same as that used by object.Equals
etc. See @dbc's awesome post for more details.
Unfortunately, since it is not really equal, null propagation doesn't kick in (since null propagation does not use the h == null
style comparison).
As such the equivalent IsNull_yes
implementation is not your existing code -
but something closer to:
public static bool IsNull_yes(dynamic source)
{
if (null == source.x || source.x.y == null) return true;
return false;
}
which acts exactly the same way (i.e. throws an exception).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With