7
??? o = new ???();

Console.WriteLine("ToString() -> " + o.ToString() ); //<--- Prints 'ToString() -> '
Console.WriteLine("GetType() -> " + o.GetType()); //<--- NullReferenceException

Output:

ToString() -> 

Unhandled Exception: System.NullReferenceException: Object reference not set 
to an instance of an object.
at System.Object.GetType()
at Program.Main(String[] args)

Question

What is the type ??? and why does o.ToString() return string.Empty and o.GetType() throws a NullReferenceException?

Note: GetType() is not redefined in the ??? type.

George Stocker
  • 57,289
  • 29
  • 176
  • 237
Jeff Cyr
  • 4,774
  • 1
  • 28
  • 42
  • 2
    If the type is `Nullable`, this will happen since `GetType` is not `virtual` and the object will have to be boxed in order to call `Object.GetType` in the base class, and a nullable type will box to null, and a method call on null will cause a NullReferenceException. This is not a real question--voted to close. – Mehrdad Afshari Feb 12 '10 at 16:04
  • 1
    Completely disagree with the close. The question is clear - what type would give a NullReferenceException. Just because the OP implies they know the answer doesn't make this "not a real question". It's some C# trivia that others can learn from. HOwever, it is now answered so reopening seems futile. – Jeff Yates Feb 12 '10 at 16:21
  • 4
    I think this is a real question. – Chris Marisic Feb 12 '10 at 16:26
  • There are two different examples on http://stackoverflow.com/questions/194484/whats-the-strangest-corner-case-youve-seen-in-c-or-net/194671#194671 – Marc Gravell Feb 12 '10 at 16:35

1 Answers1

7

Any Nullable<T>.

Check Gravell's example to strange corner cases in C#

Community
  • 1
  • 1
Dynami Le Savard
  • 4,986
  • 2
  • 26
  • 22
  • 2
    An even more interesting example is the `MyFunnyType` on the same answer. – Marc Gravell Feb 12 '10 at 16:36
  • A Nullable doesn't produce the stack trace above. The stack trace line 'at System.Object.GetType()' implies that the error is thrown from within GetType(), the Nullable situation will just throw the NullReferenceException in Program.Main. – Russell Giddings Dec 20 '12 at 17:59
  • @RussellGiddings This is not correct. The stack trace behaves as described above. Calling `GetType()` on a `null` reference type would produce a different trace but calling it on a `null` value type results in what is described above. See: https://dotnetfiddle.net/3zDtxc – Noel Widmer Oct 01 '18 at 13:01