Why does some methods work while some do not on null values of nullable structs?

.net, c#, nullable, struct

Solution

It is because `ToString` is virtual while `GetType` is not. Nullables have special boxing behavior in the CLR. When you call `GetType` on a nullable it is boxed (see MSDN, actually this happens for any `struct`). However, with a nullable, the the underlying value is boxed, not the actual nullable. `ToString` on the other hand calls the override of ToString method on `Nullable<T>`. Also, I would note that `int? i = null` is syntax sugar for `Nullable<int> i = new Nullable<int>()`. So, there really is an object in your variable `i`.

Problem

Straight to the point: ``` int? i = null; i.ToString(); //happy i.GetType(); //not happy ``` I get a very related question which actually deals on why does `i.ToString()` work fine. Edit: Just found out this corner case has been the most voted one in this SO thread!

Original source

Related problems