When I use this below code, I get object reference error, this might be because there is no match for "spider". My question is, How to check for null value in these situations
int fooID = foos.FirstOrDefault(f => f.Bar == "spider").ID;
I'm using this same scenario for different conditions for fetching different Items from the list like
int fooID = foos.FirstOrDefault(f => f.Bar == "spider").ID;
String fooDescription = foos.FirstOrDefault(f => f.Sides == "Cake").Description;
Is there any other way to check for null values.
The best way to avoid the "NullReferenceException: Object reference not set to an instance of an object” error is to check the values of all variables while coding. You can also use a simple if-else statement to check for null values, such as if (numbers!= null) to avoid this exception.
FirstOrDefault returns the default value of a type if no item matches the predicate. For reference types that is null . Thats the reason for the exception.
The same way as you normally would, assign a variable and check it.
var foo = foos.FirstOrDefault(f => f.Bar == "spider");
if (foo != null)
{
int fooID = foo.ID;
}
Based upon your updated example, you would need to do this 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 you would want to use if there is no matching description.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With