Reputation: 11119
Seems like a bug to me.
var obj = JsonConvert.DeserializeObject<dynamic>("{\"arr\": [{\"prop1\": null}]}");
var prop1 = ob.arr[0].prop1; // has {} value
var test = ob.arr[0].prop1?.prop2; //causes error
'Newtonsoft.Json.Linq.JValue' does not contain a definition for 'prop2'
Upvotes: 2
Views: 605
Reputation: 270
ob.arr[0].prop1
is not null (it is a non-null empty JValue
), so the null coalescing operator doesn't halt the access chain.
Instead ob.arr[0].prop1.Value
is null, so you may use:
var test = obj.arr[0].prop1.Value?.prop2;
or
var test = obj.arr[0].prop1.HasValues
? obj.arr[0].prop1.prop2 // this will be null in your case
: null;
Upvotes: 2