Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I get a NullReferenceException in this code sample?

Tags:

c#

.net

??? 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.

like image 454
Jeff Cyr Avatar asked Feb 12 '10 16:02

Jeff Cyr


1 Answers

Any Nullable<T>.

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

like image 116
Dynami Le Savard Avatar answered Oct 14 '22 08:10

Dynami Le Savard