The debugger is showing the wrong line as the exception source. This does happen sometimes, you need to keep an eye on the surrounding code, and the stack trace.
Since you're working with a web application, it's also quite possible that the debugging information is out of sync with the code. Rebuilding the whole project might help, unless your dependencies are badly arranged.
Look at code ahead of the comparison, and below it as well (Is Session
null? Is Session.UserId
null? Is SqlCommands.LookupInsertCommand
throwing NullReferenceException
?). You can use quick watch to check pieces of code and find the one causing the NullReferenceException
.
As a side-note, try not to carry practices from other languages to C#. Initialize local variables when you actually have a reasonable value to initialize them with - don't worry, the compiler will not allow you to compile code reading a variable that hasn't been assigned yet. When you just assign a default value, you're losing out on a few sanity checks of the code. Also, don't compare constant == variable
. There's no reason to do that in C#, because you can't just accidentally type variable = constant
- it will not compile (the only exception being the bool
type, but you shouldn't compare that to a constant anyway - just do if (boolValue)
or if (!boolValue)
). It just makes the code harder to read and understand.
EDIT:
This case in particular is actually quite obvious if you know what you're looking for. You see, the if (0 == lookupValue)
doesn't exist anywhere in the compiled binary - the compiler can safely ignore it, because lookupValue
will always be 0
. Usually, the debugging information will account for this, but missing by one line is quite common even when there's nothing as drastic as a whole missing line of code (in your case, likely more than one).
Since you are working with an ASP.NET application, part of the code isn't actually compiled by Visual Studio - it's compiled when you make a request. To generate proper debug information, you must also set the <compilation debug="true" />
in web.config
(Compilation element).