1

I have some code that throws a null reference error:

72    if (query.allergy != null && query.allergy.Count > 0)
73    {
74        for (var i = 0; i < (query?.allergy?.Count ?? 0); i++) // <-- this line throws null reference exception

It seems I have null-checked everything here. How can it possibly throw a null reference error?

I don't have a chance to debug this remotely, so I don't know which part of the code is null.

Stack trace:

Object reference not set to an instance of an object. at XXXXXXXXX.Helpers.ProductHelper.processEntities(List`1 entities, String language) in C:\Users\XXXXXX\Dropbox\code\bots\XXXX\Helpers\ProductHelper.cs:line 74

I'm sure about the line number, I shifted the code by a few lines to make sure that this is this line, and the line number changed.

  • 4
    What if query is null? (I'm talking about if (query.allergy != null....)) – Matteo Umili Sep 01 '17 at 08:05
  • Are you sure the exception is thrown in the `for` line and not in the `if` one? – Pikoh Sep 01 '17 at 08:06
  • Are you sure it's that line and not the one above: `if (query.allergy...` could throw if `query` is null. – René Vogt Sep 01 '17 at 08:06
  • 4
    Please add the stacktrace. You have nearly 4k rep. You should know [ask]. ;) – Fildor Sep 01 '17 at 08:06
  • @Pikoh Absolutely sure by looking at stack trace –  Sep 01 '17 at 08:07
  • 1
    @Fildor added stacktrace –  Sep 01 '17 at 08:09
  • 3
    Please show a [mcve]. We can't really help with just this snippet. – Jon Skeet Sep 01 '17 at 08:09
  • 1
    Either your debugging symbols are wrong/off (something even optimization can do), causing the stack trace to misreport the actual line, or you've got an even less probable error in the JIT compiler. – Jeroen Mostert Sep 01 '17 at 08:15
  • @JeroenMostert Bingo! You were right. The offending code was a few lines lower. How the hell can the debugging symbols be off by a few lines? –  Sep 01 '17 at 08:17
  • 2
    Excellent question. Make it a separate one, maybe the MS developers will finally weigh in. :-) In short, though, while the debugging symbols reference the IL, I think occasionally the ball is dropped when the JIT compiler optimizes the code and doesn't get the references quite right as it shuffles around code. I think the C# compiler itself is blameless. But this is pure speculation on my part, even though I've seen it happen lots of times. When you get a curious stack trace, always try to repro on a debug build first, it's more reliable. – Jeroen Mostert Sep 01 '17 at 08:20
  • 1
    @K48 When you are sure that `query != null`, then you can remove all null propagation operator within the `for` loop. – Martin Backasch Sep 01 '17 at 08:21

0 Answers0