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.

4
  • 2
    If the type is Nullable<T>, 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. Commented Feb 12, 2010 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. Commented Feb 12, 2010 at 16:21
  • 4
    I think this is a real question. Commented Feb 12, 2010 at 16:26
  • There are two different examples on stackoverflow.com/questions/194484/… Commented Feb 12, 2010 at 16:35

1 Answer 1

7

Any Nullable<T>.

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

Sign up to request clarification or add additional context in comments.

3 Comments

An even more interesting example is the MyFunnyType on the same answer.
A Nullable<T> 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<T> situation will just throw the NullReferenceException in Program.Main.
@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: dotnetfiddle.net/3zDtxc

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.