Amazon.com Widgets

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. 

Published 26 February 04 08:54 by BradA
Filed under:

Comments

# Raymond Chen said on February 26, 2004 9:33 PM:
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.
# Jelle Druyts said on March 11, 2004 12:18 AM:
Thanks for the t-shirts and the note :-)
# Brad Abrams said on March 13, 2004 4:50 PM:
# Brad Abrams said on August 7, 2004 11:45 PM:
# Brad Abrams said on August 8, 2004 10:16 AM:
# (luKa) said on September 11, 2004 8:57 AM:
# Impersonation Failure said on July 26, 2006 3:24 AM:
We ran into an interesting bug a couple of days back where some code would work on a developers machine
New Comments to this post are disabled

Search

Go

This Blog

Syndication

Page view tracker