0

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)?

Lesmian
  • 3,932
  • 1
  • 17
  • 28
  • 4
    What happens if you use `request?.Event?.Id`? – mjwills Dec 10 '17 at 10:52
  • @mjwills well that works, but why I have to use question mark everywhere? Shouldn't it stop executing the statement on first null? – Lesmian Dec 10 '17 at 10:55
  • 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 Dec 10 '17 at 10:56
  • @Igor Ok, I'll walk myself out... Apparently, I stay at work to long. I see my obvious mistake now :) – Lesmian Dec 10 '17 at 10:59
  • 3
    https://stackoverflow.com/questions/2080647/deep-null-checking-is-there-a-better-way would likely be a 'better' duplicate than the one that was chosen. – mjwills Dec 10 '17 at 11:02

1 Answers1

2

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
Igor
  • 60,821
  • 10
  • 100
  • 175