11

I just got this quiz from a colleague that is driving me crazy. For this snippet of code:

var x = new Int32?();
string text = x.ToString(); // No exception
Console.WriteLine(text);
Type type = x.GetType(); // Bang!

Why does the first part .ToString() works without throwing an exception and then the call to GetType() throws a NullReferenceException ?

1 Answer 1

20

ToString is overridden in Nullable<T>, so no boxing is involved to make the call.

GetType() isn't a virtual method, so isn't (and can't be) overridden, so the value is boxed before the call is made... and boxing a null value of a nullable value type gives a null reference.

The reason for boxing is in section 7.5.5 of the C# 4 spec:

If M is an instance function member declared in a reference-type:

  • ...
  • If the type of E is a value-type, a boxing conversion (4.3.1) is performed to convert E to type object, and E is considered to be of type object in the following steps. In this case, M could only be a member of System.Object

Note that if you had:

var x = new Int32?(10);

you'd end up with the type being the same as typeof(int), again due to boxing. There is no way of creating a value foo such that foo.GetType() returns a nullable value type, using the normal GetType() method. (You could create a new GetType() method of course, but that's a side issue :)

(The use of "Bang!" suggests the author of said quiz may be me. Apologies for driving you crazy if that's the case.)

3
  • Ok .. but why then replacing the last line with: var boxed = (Int32) x; throws InvalidOperationException instead? Isn't that boxing and should throw the same exception?
    – kabaros
    Oct 4, 2012 at 10:53
  • @kabaros: No, that's not boxing at all - neither Int32? nor Int32 are reference types. It's an explicit conversion described in section 6.2.3 of the C# 4 spec.
    – Jon Skeet
    Oct 4, 2012 at 10:56
  • 1
    Oh yeah of course, that makes perfect sense. Thanks a lot. Great book by the way so you're forgiven for driving us crazy :)
    – kabaros
    Oct 4, 2012 at 10:57

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.