Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

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.

like image 893
Mohan Avatar asked Apr 18 '13 11:04

Mohan


People also ask

How do I fix NullReferenceException Object reference not set to an instance of an object?

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.

Does FirstOrDefault return null?

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.


1 Answers

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.
like image 142
Trevor Pilley Avatar answered Sep 21 '22 17:09

Trevor Pilley