Getting a variable name for a NullReferenceException

Stack NullReferenceException for NullReferenceException very uninformative, they just include the method name and call stack. Any variable in a method can be null, and it is difficult to debug when an error is not reproduced on the dev machine.

Do you know how to get additional information about this error, perhaps get the variable name? Or do you have better ways to debug it?

+5
source share
1 answer

Tracking this name is not always possible (it may be an expression).
And where possible, this will entail unacceptable overhead. Consider that at runtime you will need to keep track of almost all the reference variables, which would be expensive and prohibit all kinds of optimizations.

Also see my answer to Inspect the managed stack and the blog post it links to.

A simple solution is to build a more consistent null check in your own code:

 void Foo(Bar b) { if (b == null) throw new ArgumentNullException(nameof(b)); ... } 
+9
source

Source: https://habr.com/ru/post/1239082/


All Articles