NullReferenceException when using Null-conditional Operator with object initializer [duplicate]

问题内容:

This question already has an answer here:

Why I get System.NullReferenceException running a code like:

var Response = new Response()
{
    Id = request?.Event.Id
};

Shouldn’t I just get Null value for Id property (Id is a string)?

问题评论:

4  
What happens if you use request?.Event?.Id?
    
@mjwills well that works, but why I have to use question mark everywhere? Shouldn’t it stop executing the statement on first null?
– Lesmian
yesterday
3  
Your current code only take into account if request is null and Event will not be returned if that was the case. If Event is null in the request instance then that would still lead to an NRE when you try to access the Id property.
    
@Igor Ok, I’ll walk myself out… Apparently, I stay at work to long. I see my obvious mistake now 🙂
– Lesmian
yesterday
3  
stackoverflow.com/questions/2080647/… would likely be a ‘better’ duplicate than the one that was chosen.

答案:

答案1:

Your current code only take into account if request is null and Event will not be returned if that was the case. If Event is null in the request instance then that would still lead to an NRE when you try to access the Id property.

The fix is to also add the null conditional operator to Event which will return null if Event is null and not try to access Id.

request?.Event?.Id

答案评论:

原文地址:

https://stackoverflow.com/questions/47738062/nullreferenceexception-when-using-null-conditional-operator-with-object-initiali

Tags:,

添加评论