Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting the variable name for NullReferenceException

Stack traces for NullReferenceException is very uninformative, they just include the method name and the call stack. Any variable in a method can be null and it's hard to debug when the bug isn't reproducible on the dev machine.

Do you know a way to get more info on that error, getting the variable name perhaps? Or do you have better ways to debug it?

like image 359
Elmo Avatar asked Dec 23 '15 19:12

Elmo


1 Answers

Keeping track of that name is not always possible (it could be an expression).
And where it is possible it would incur unacceptable overhead. Consider that the runtime would have to track almost all reference variables, that would be costly and prohibit all sorts of optimizations.

Also see my answer on Inspect the managed stack and the Blog post it refers to.

The simple solution is to build in more consistent null checking in your own code:

void Foo(Bar b)
{
   if (b == null) throw new ArgumentNullException(nameof(b));

   ...
}
like image 158
Henk Holterman Avatar answered Oct 09 '22 20:10

Henk Holterman