Null-coalescing operator in conjuction with JObject

373 views Asked by At

I have below code written to read JArray from a given JObject.

To my understanding, when the value of "tags" in JObject is null, IEnumerable should be initialized as empty.

IEnumerable<string> tags = eventPayload?["tags"]?.Values<string>() ?? Enumerable.Empty<string>();

However, this lines throws exception when json looks like

{
    "tags": null   
}

System.InvalidOperationException
  HResult=0x80131509
  Message=Cannot access child value on Newtonsoft.Json.Linq.JValue.

If I were to make above line read null and initialize enumerable as empty, what changes do I need to make?

1

There are 1 answers

1
Eugene Shvets On

The issue is that eventPayload?["tags"] is JValue.Null, not null.