c# - Object Reference Not set to instance of an object error while using FirstOrDefault -


when use below code, object reference error, might because there no match "spider". question is, how check null value in these situations

int fooid = foos.firstordefault(f => f.bar == "spider").id; 

i'm using same scenario different conditions fetching different items list

int fooid = foos.firstordefault(f => f.bar == "spider").id;  string foodescription = foos.firstordefault(f => f.sides == "cake").description;  

is there other way check null values.

the same way would, assign variable , check it.

var foo = foos.firstordefault(f => f.bar == "spider");  if (foo != null) {     int fooid = foo.id; } 

based upon updated example, need instead:

var fooforid = foos.firstordefault(f => f.bar == "spider"); var foofordescription = foos.firstordefault(f => f.sides == "cake");  int fooid = fooforid != null ? fooforid.id : 0; string foodescription = foofordescription != null ? foofordescription.description : null; // or string.empty or whatever want use if there no matching description. 

Comments

Popular posts from this blog

Why does Ruby on Rails generate add a blank line to the end of a file? -

keyboard - Smiles and long press feature in Android -

node.js - Bad Request - node js ajax post -