0

why c# code

            DateTime? temp = null;
            Console.WriteLine(string.IsNullOrWhiteSpace(temp.ToString()));

just print out "True" and do not throw null object Exception?

have run this code in Debug and Release build both do not throw exception using .NET Framework 4.7.2

2 Answers2

3

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

Luaan
  • 62,244
  • 7
  • 97
  • 116
1

Because the Nullable<DateTime> returns an empty string if its HasValue property is "false".

Here's the documentation: https://learn.microsoft.com/en-us/dotnet/api/system.nullable-1.tostring?view=netframework-4.7.2

Shazi
  • 1,490
  • 1
  • 10
  • 22