C# – Why NullReferenceException Lacks Null Information

c++

What was the design decision behind NullReferenceException not containing any runtime specific information except base class data (like a stacktrace)? And is there an extension for Visual Studio that can tell you straight away which part of an expression was null?

Best Answer

An NRE is a very low-level exception. It is a hardware exception (a 'trap') generated by the processor when it is asked to read data from an address below 64K. That region of the virtual memory space is always unmapped, specifically to trap pointer bugs. It starts as an AccessViolation and gets turned into NRE by the CLR when the address is less than 0x00010000. At that point there is very little context for the exception, all that's known is the address of the machine code instruction that caused the trap.

Reverse-engineering that machine code instruction address back to a named variable in your program isn't possible. It is important that it works that way, a jitter would have to generate very inefficient code otherwise. All that can be reasonably done is recover the source code line number. That requires debugging info (a .pdb) that contains line number info. The CLR knows how to read the .pdb file and uses it to generate the exception's stack trace. However, this is often still inaccurate due to optimizations performed by the JIT optimizer, it moves code around. You'll only get a guaranteed match for the Debug build. The reason why the PDB for the Release build doesn't contain source line number info. You can change that.

This problem has a very simple solution. Check for null yourself and generate your own exception before letting the runtime do it. The test is quite cheap, well less than a nanosecond.

Related Question