Thursday, August 21, 2008

The not so nullable .NET Date Data Type!

Can a variable of type "Date" ever be null or nothing in VB.NET? Suppose you have a code that looks like this:

What you will notice in the above code is that even if you set the variable to "Nothing" for a variable of type "Date", when you put a break point and look inside the variable, it shows the value #12:00:00 AM#! You may feel cheated at this point and throw your hands up, shouting "What gives?" Don't give up quite yet though, because your value of nothing IS actually in there. Try modifying the code to the following now:

Run the code, and you will get a message prompt indicating that the variable does in fact contain "Nothing"!

That's because for a variable of type "Date" in .NET, #12:00:00 AM# is infact "Nothing"! If you really have your heart set on having nothing in the Date variable, you can try this instead:

Obvious to some people, not so obvious for others. Lesson learned.

Pete Soheil
DigiOz Multimedia

No comments: