When exactly do nullable types throw exceptions?

  • A+

Consider the following code:

int? x = null; Console.Write ("Hashcode: "); Console.WriteLine(x.GetHashCode()); Console.Write("Type: "); Console.WriteLine(x.GetType()); 

When executed, it writes that Hashcode is 0, but fails with NullReferenceException in attempt to determine type of x. I know that methods called on nullable types are actually called on underlying values, so I expected program to fail during x.GetHashCode().

So, what is the fundamental difference between those two methods and why doesn't the first of them fail?

This is because int? x = null; essentially creates an instance of the value type System.Nullable<int>, with an "inner" null value (you can get it via .Value Property). When GetHashCode is invoked, the override Nullable<int>.GetHashCode is the method candidate (since the method is virtual), now we have an instance of Nullable<int>, and execute its instance method, perfect.

When invoking GetType, the method is non-virtual, so the instance of Nullable<int> is boxed to System.Object first, according to the document, and boxed value is null, hence the NullReferenceException.


:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: