简体   繁体   中英

How to make the variable empty if the Jobject is empty in C#

I am getting a Null reference exception when the Jobject is empty.

var subjects = item.SelectToken("$.subjects").ToObject<List<JObject>>()

I am want to set var subjects as empty when Jobject empty without throwing an error.

THanks

var subjects = item.SelectToken("$.subjects")?.ToObject<List<JObject>>() ?? new List<JObject>();

List<...>

List is a collection and you need to define what's in the List. Like List<string> , List<object> , or, for your code, List<JObject> .

SelectToken("$.subjects")?.

This means that if SelectToken returns null, it stops there without doing .ToObject , and returns null .

The issue here is that SelectToken will return null when it can't find any object, and when you do .ToObject on a null you get a NullException . So one'd usually check if an object is null before further using its properties or functions.

The question mark - Null-Conditional Operator ( Official documents ) is a quick syntactic sugar to achieve that, without having to write conditions like

if (... == null) 
{ ...convert to list... } 
else 
{ ...make empty list...}

?? new List()

Not sure what you mean by empty , if you don't want null , but an empty List , Null-coalescing Operator might come to help.

It means that if the statement before ?? is null , returns the statement after ??instead.

For example, string a = b ?? c string a = b ?? c means:

string a = b != null ? b : c

But notice that a still can be null if c is null .

It's also a syntactic sugar to help you avoid writing long statements for these checks are frequently needed.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM