C
C#•3y ago
sonodan.

Dereference of a possibly null reference [Answered]

I'm making a HTTP call and I get the aforementioned warning (also see attached). I thought my if-else check would handle this. Any guidance? Thanks in advance!
9 Replies
TheRanger
TheRanger•3y ago
yes jsonResponse itself may not be null in this case but PageData is possible it can have 0 elements
sonodan.
sonodan.•3y ago
so is best practice to check PageData.Count > 0?
TheRanger
TheRanger•3y ago
yes if you are sure PageData.Count will never be 0 just use First() instead or .FirstOrDefault()! to tell the compiler that this will never return null to shut off the warning
sonodan.
sonodan.•3y ago
I went with adding
jsonResponse is null || PageData.Count() == 0
jsonResponse is null || PageData.Count() == 0
and then also used .First() on the else return. Thanks for the help! 🙂
Unknown User
Unknown User•3y ago
Message Not Public
Sign In & Join Server To View
Monsieur Wholesome
Monsieur Wholesome•3y ago
My lazy butt would likely just do
return jsonResponse.Content.Pages.Page.PageData.FirstOrDefault()?.SectionContent ?? String.Empty;
return jsonResponse.Content.Pages.Page.PageData.FirstOrDefault()?.SectionContent ?? String.Empty;
ero
ero•3y ago
don't use Count() == 0 the compiler should suggest using !PageData.Any()
Unknown User
Unknown User•3y ago
Message Not Public
Sign In & Join Server To View
Accord
Accord•3y ago
✅ This post has been marked as answered!
Want results from more Discord servers?
Add your server