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 🙂

 

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s