1

I'm getting this error:

Cannot perform runtime binding on a null reference

When I try to assign a JSON object to a var

var vrlvl = dataFirst.payload.last_quick_matches.csgo.skill_level;

How do you check if a object is null before you assign it?

I've tried these, but it gives the same error

if (dataFirst.payload.last_quick_matches.csgo.skill_level != null)

if (Object.ReferenceEquals(null, dataFirst.payload.last_quick_matches.csgo.skill_level)) 

1 Answers1

0

You might need to check a few levels up too:

if (dataFirst && dataFirst.payload && dataFirst.payload.last_quick_matches && dataFirst.payload.last_quick_matches.csgo && dataFirst.payload.last_quick_matches.csgo.skill_level)
{
    var vrlvl = dataFirst.payload.last_quick_matches.csgo.skill_level;
}

Edit: try this:

if (dataFirst != null && dataFirst.payload != null && dataFirst.payload.last_quick_matches != null && dataFirst.payload.last_quick_matches.csgo != null && dataFirst.payload.last_quick_matches.csgo.skill_level != null)
{
    var vrlvl = dataFirst.payload.last_quick_matches.csgo.skill_level;
}
IAmCoder
  • 3,179
  • 2
  • 27
  • 49
  • This returns the error `Cannot implicitly convert type 'Newtonsoft.Json.Linq.JObject' to 'bool'. An explicit conversion exists (are you missing a cast?)` – Kingsmeister Mar 17 '18 at 13:24
  • I was thinking in JavaScript - I made an edit that should work now... – IAmCoder Mar 17 '18 at 13:35
  • 1
    The conditional statement can be shortened to `if (dataFirst?.payload?.last_quick_matches?.csgo?.skill_level != null)`. – ckuri Mar 17 '18 at 14:03