I was looking into nullable bools when I found this article on Microsoft MSDN
How to: Identify a Nullable Type (C# Programming Guide)
You can use the C# typeof operator to create a Type object that represents a Nullable type.
So I tried checking with a nullable bool:
Console.Write(typeof(bool?)); //System.Nullable`1[System.Boolean]
The article on MSDN says
You can also use the classes and methods of the System.Reflection namespace to generate Type objects that represent Nullable types. However, if you try to obtain type information from Nullable variables at runtime by using the GetType method or the is operator, the result is a Type object that represents the underlying type, not the Nullable type itself.
Calling GetType on a Nullable type causes a boxing operation to be performed when the type is implicitly converted to Object. Therefore GetType always returns a Type object that represents the underlying type, not the Nullable type.
If this is true I expect to get the same result from .GetType()
whether I use a nullable bool or a regular bool. But this is not what happens:
bool a = new bool();
Console.Write(a.GetType()); //Prints System.Boolean
bool? b = new bool?();
Console.Write(b.GetType()); //Exception!
The exception that occured:
An unhandled exception of type 'System.NullReferenceException' occurred in BoolTest.exe
Additional information: Object reference not set to an instance of an object.
But the object reference is set to an instance of an object. What could be the cause of this error?
See Question&Answers more detail:os