jason jason - 1 month ago 11
C# Question

Null Reference exception in FirstOrDefault C#

I have this line:

myobject.Ada = result.FirstOrDefault(m => m.Name == "Ada No").Value;


Sometimes result doesn't have "Ada No" and I get


Object reference not set to an instance of an object.


I wrote an if statement to avoid null reference exception :

if(result.FirstOrDefault(m => m.Name == "Ada No").Value != null)
{
myobject.Ada = result.FirstOrDefault(m => m.Name == "Ada No").Value;
}


But it didn't work either. How can I avoid this exception in this piece of code? How can I write if Ada No exists, work, if not don't work? Thanks.

Answer

FirstOrDefault will return null if there is not any object which meets the condition. And the exception will be thrown when the code is trying to access a member of a reference type variable that is set to null. So, you must check if the object's value is null or not before accessing it.

You can use null-propagation operator if you are using C# 6.0:

myobject.Ada = result.FirstOrDefault(m => m.Name == "Ada No")?.Value;

Or if you are using lower versions:

var firstObj = result.FirstOrDefault(m => m.Name == "Ada No");

if(firstObj != null)
{
    myobject.Ada = firstObj.Value;
}