C
C#2y 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
TheRanger2y ago
yes jsonResponse itself may not be null in this case but PageData is possible it can have 0 elements
sonodan.
sonodan.2y ago
so is best practice to check PageData.Count > 0?
TheRanger
TheRanger2y 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.2y 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 User2y ago
Message Not Public
Sign In & Join Server To View
Monsieur Wholesome
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
ero2y ago
don't use Count() == 0 the compiler should suggest using !PageData.Any()
Unknown User
Unknown User2y ago
Message Not Public
Sign In & Join Server To View
Accord
Accord2y ago
✅ This post has been marked as answered!