As part of a significant refactoring effort, I was moving code from one project to another and accidentally made a change that resulted in a much different result than I expected. I'm getting a date from a database query, but that date column allows nulls. Here's what I had before:
DateTime? someDate = (dataReader["DATE_COLUMN"]) != null
? Convert.ToDateTime(dataReader["DATE_COLUMN"])
: new DateTime?();
And here's what I ended up typing in my refactored code:
DateTime? someDate = (dataReader["DATE_COLUMN"]) != null
? Convert.ToDateTime(dataReader["DATE_COLUMN"])
: default(DateTime);
I didn't even realize I'd written the code differently, probably because they should have the same result, but they didn't. The first version,
new DateTime?(), has the value
null, while the second version,
default(DateTime), has the value
1/1/0001. That's not even a valid date in SQL Server!
The following code in a console application will demonstrate different default values.
Console.WriteLine("new DateTime?() = {0}", new DateTime?());
Console.WriteLine("default(DateTime) = {0}", default(DateTime));
Console.WriteLine();
Console.WriteLine("new TimeSpan?() = {0}", new TimeSpan?());
Console.WriteLine("default(TimeSpan) = {0}", default(TimeSpan));
It looks like a new instance of a nullable object will always be null, while the default value for that type won't be null. Of course, I came to this conclusion with very limited tests, but it's good enough for me.

Labels: c#