C# in Depth

Cover of C# in Depth
Order now (3rd edition)

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:

int? foo = null;
int hash = foo.GetHashCode();
string text = foo.ToString();
bool equal = foo.Equals(foo);
Type type = foo.GetType();

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 GetType does end up boxing the value into a null reference, which then causes a NullReferenceException.

Many thanks to Marc Gravell for this interesting example.