If you compile
object o = null; int a = (int)o;
and look at the MSIL code, you will see something like
ldnull ... unbox.any int32
Now the behavior for unbox.any is as follows:
An InvalidCastException is thrown if obj is not a boxed type.
Throw NullReferenceException if obj is a null reference.
This is what you see in your code.
source share