Matt Casto's .NET Journal RSS 2.0
 Tuesday, July 10, 2007
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));

Console Output

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:

Tuesday, July 10, 2007 6:20:00 AM (Eastern Standard Time, UTC-05:00)  #    Comments [4] -
c#
About the author/Disclaimer

Disclaimer
The opinions expressed herein are my own personal opinions and do not represent my employer's view in any way.

© Copyright 2009
Matt Casto
Sign In
All Content © 2009, Matt Casto
Theme based on DasBlog theme 'Business' created by Christoph De Baene (delarou)