C# compiler Fails to Fail-Fast

If title didn’t made sense,ย  I believe at least the post will ๐Ÿ™‚

When you invoke a method on a null instance inย  C# NullReferenceException will be thrown unlike C++/CLI which allows instance methods to be called with null references.

C# compiler does this with the help of callvirt opcode. As we saw earlier that the compiler emits call opcode when it can prove that the object reference is not null.

Compiler is trying to be smart and optimizes the callvirt to call opcode as we saw in my last post. I agree; compiler is smart, but not smart enough.

Yeah, compiler made a brave assumption that new operator will never return null. But that’s a false assumption. New operator returns null in this corner case.

Consider my following contrived example:

Clearly the above code shows that the code explodes in middle of the method(where this pointer is dereferenced) with NullReferenceException and not at the very beginning of the method call itself.

The C# compiler failed to Fail Fast and thus the title ๐Ÿ™‚