posted on Monday, March 15, 2004 10:54 AM
by
samunro
Representing Null DateTime values in code.
How do you handle a null DateTime value? DateTime is a value type and so you can not simply set it to a value of null. Initialise it with 0, (ticks), then calling ToString returns the following.
1/01/0001 12:00:00 AM
I realise it would be a fairly exceptional case that you would actually have a real value that would conflict with this but it still feels a bit like we are just crossing our fingers and hoping for the best.
We could add code to check for this value every time that we access a DateTime variable but that sounds a bit tedious. We could use the NullObject design pattern to solve this problem however we are not able to inherit from value types which, the implementation of the design pattern calls for.
I have in the past wrapped DateTime in a class that delegates most methods to its private DateTime field but where an implementation that makes sense for a null value it intercedes. The obvious example is ToString which can be used to return something like “Null”. You could of course make it more complete by returning a different string depending on the culture but I am sure you get the idea.
I read recently in Kathleen Dollard's code generation book that Rocky Lhotka uses a SafeDateTime in his CSLA framwork but for the life of my I can't find a reference to it on the net. I think it was pretty much the same concept though.
These all seem like more work than should be required. Why is DateTime a value type? Anyone from the BCL Team got some background on this?