A winner for my little quiz on NullReferenceException

In a previous post I asked

I said that we throw a NullReferenceException when you try to access instance “state” (eg a field).  What if you have an instance method that does not touch any instance state (for example an instance method that just does a Console.WriteLine (“hello“)).  Will you get a NullReferenceException when you call that?  Why?  Hint: It is one of those interesting differences between the CLR and the C# programming language. 


Jelle Druyts responded on his blog with the right answer.  Essentially the C# language specification requires that any method call on a null instance result in a NullReferenceException, this is done to provide more predictability to the language, and frankly, I can’t say I blame them.  But at the CLR level, we can’t assume that every language will follow suit, so we provide the call instruction which will not check for null and callvirt that will.  C# gets its semantics by always using callvirt for any instance calls. 


Jelle send me your snail mail address so I can send you very small prize for answering my quiz. 

Comments (7)

  1. Raymond Chen says:

    And this is why, when you’re looking at JITted code, you’ll see seemingly pointless instructions like

    test [ecx], ecx

    The purpose of this instruction is to raise the NullReferenceException when necessary.

  2. Jelle Druyts says:

    Thanks for the t-shirts and the note 🙂

  3. We ran into an interesting bug a couple of days back where some code would work on a developers machine