Reputation: 7164
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.
Upvotes: 0
Views: 3674
Reputation: 864
The other solution would be to check with Any if any member is existing that consists of Name equal to "Ada No"
Be aware that result
isn't null either!
But the null propagation way would be less to write, so it depends on you preference how you want to read your code and if it is some performance critical piece of code
if(result != null && result.Any(m => m.Name == "Ada No"))
{
myobject.Ada = result.FirstOrDefault(m => m.Name == "Ada No").Value;
}
Upvotes: 2
Reputation: 26635
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;
}
Upvotes: 8