Totallama Totallama - 1 month ago 12
C# Question

C# Exception: Cannot perform runtime binding on a null reference while checking whether it is null or not

I simply need to check whether the object is not null before actually using it but it keeps throwing this exception:
Cannot perform runtime binding on a null reference

if (interMarket.marketItems.prices != null) {
// do something..
}


interMarket
contains data from JSON.

What am I doing wrong?

Answer

What specific exception is being thrown? Where is it being thrown in your code? Is it possible that interMarket or interMarket.marketItems is null? If so, using the null conditional operator (?.) will fix the issue:

if (interMarket?.marketItems?.prices != null) {
// do something..
}