Null references vs null values

Chapter 10: Extension methods: 10.2.4

Created: 4/2/2008
Last updated: 4/2/2008

As I mention in section 10.2.4 when describing extension methods, "You can't call instance methods on null references in C#". This is correct (with the understanding that calling an extension method using a null target isn't the same as calling a true instance method) but life becomes more interesting when you consider null values in general. In particular, Nullable<T> allows various methods to be called on a null value. Consider the following code:

Without peeking back at chapter 4, what would you expect the results to be? As it happens, the code above does blow up with an exception - but only on the last line. The first three method calls require no boxing, and Nullable<T> handles them just fine. The call to GetTypedoes end up boxing the value into a null reference, which then causes a NullReferenceException.