Nullable is a struct. You can call methods on empty structs just fine, and ToString
for an empty nullable returns string.Empty
. No magic involved :)
The only real magic with nullables has to do with boxing. When you box, say, an integer, you get a boxed integer ((object)10
returns an object
which can be cast to int
- and actually only int
). But when you box a nullable integer without a value, you actually get null
, not a boxed nullable integer (while a nullable integer with value will turn into a perfectly normal int
when boxed, not int?
). So:
DateTime? temp = null;
var boxedTemp = (object)temp;
Console.WriteLine(string.IsNullOrWhiteSpace(boxedTemp.ToString()));
will actually throw, because boxedTemp is a null reference (while temp is not a reference in the first place, so it can't be a null reference specifically).