I have a simple test code that works as expected in .NET3.5, but the same code behaves completely different on a project created with .NET4.5.1.
class Program
{
string a = null;
var x = a.Length;
In RELEASE mode, the jitter (just in time compiler) is able to prove that x
is never referenced, so is able to remove the assignment.
In DEBUG mode, the jitter does not perform that optimization.
To force the exception to be thrown, do something with x
(e.g. as @Henk suggests in the comments, WriteLine(x)
).
EDIT
Eric Lippert noted in the comments
...I am as surprised as anyone that the jitter would elide a string length instruction that could throw. That seems wrong to me...
The jitter optimization may be overly-aggressive.