Nullable DateTime variables

  • Thread starter Thread starter Child
  • Start date Start date
C

Child

I have a class object with a couple of datetime variables that are not
required (for example the closing date for an event). I have been doing
some research on usenet history to find that this is confusing to manage and
that in different versions of ASP .Net this is handled differently.

While the database field is a datetime (nullable) the class variable doesn't
need to be.

What would be the best way to handle this variable?
 
The Date variable type cannot be null. It must have a value.
Most people use Date.MinValue (or Date.MaxValue) to represent a null date in
their code.

Example:
Dim MyDate as Date = Date.MinValue

As for inserting it in the database, the other guys already specified that
DBNull.Value is what you'll want to use.

The better news is that in .NET 2.0 all variable types will be nullable.
Here's more info:
http://www.panopticoncentral.net/archive/2004/06/04/1180.aspx
 
The better news is that in .NET 2.0 all variable types will be
nullable.

Well, the problems with this are 1) The SqlServer specific ADO.NET APIs don't
support them (like they do for the SqlXxx types) and 2) The logic of the
nullable types is not the same as the logic mandated by a database. For example:

void Main()
{
SqlInt32 x = SqlInt32.Null;
SqlInt32 y = 5;
Console.WriteLine(x == y);

int? x2 = null;
int? y2 = 5;
Console.WriteLine(x2 == y2);
}

This prints out:
Null
False

The later does not jive with what a DBA would say :)

-Brock
DevelopMentor
http://staff.develop.com/ballen
 
And I guess to follow up on this, the obvious question would be "Umm, ok,
then where are these useful?". Well, it turns out they serialize quite well
to XML when using the XmlSerializer, as they'll emit xsi:nil='true' attribute
when Nullable<T>.HasValue == false. Whether or not that's worth a change
in the language, you be the judge :)

-Brock
DevelopMentor
http://staff.develop.com/ballen
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Back
Top