Coder Perfect

DateTime “null” value

Problem

I’ve been searching a lot but couldn’t find a solution. How do you deal with a DateTime that should be able to contain an uninitialized value (equivalent to null)? I have a class which might have a DateTime property value set or not. I was thinking of initializing the property holder to DateTime.MinValue, which then could easily be checked. I guess this is a quite common question, how do you do that?

Asked by Mats

Solution #1

For normal DateTimes, if you don’t initialize them at all then they will match DateTime.MinValue, because it is a value type rather than a reference type.

You can also use a DateTime that is nullable, such as this:

DateTime? MyNullableDate;

Alternatively, you can use the longer form:

Nullable<DateTime> MyNullableDate;

Finally, there’s a built-in way to refer to any type’s default. For reference types, this returns null, however for our DateTime example, it will return DateTime. MinValue:

default(DateTime)

or, if you’re using a more modern version of C#,

default

Answered by Joel Coehoorn

Solution #2

You can use the nullable type if you’re using.NET 2.0 (or later):

DateTime? dt = null;

or

Nullable<DateTime> dt = null;

then later:

dt = new DateTime();

You can also double-check the value with:

if (dt.HasValue)
{
  // Do something with dt.Value
}

You can also use it like this:

DateTime dt2 = dt ?? DateTime.MinValue;

More information is available at http://msdn.microsoft.com/en-us/library/b3h38hb0.aspx.

Answered by Mark Ingram

Solution #3

It is also possible to use the following method.

myClass.PublishDate = toPublish ? DateTime.Now : (DateTime?)null;

Please keep in mind that the PublishDate property should be a DateTime?

Answered by Aleksei

Solution #4

DateTime? MyDateTime{get;set;}

MyDateTime = (dr["f1"] == DBNull.Value) ? (DateTime?)null : ((DateTime)dr["f1"]);

Answered by Iman

Solution #5

I’d think about utilizing nullable types.

Instead of DateTime myDate, use myDate.

Answered by David Mohundro

Post is based on https://stackoverflow.com/questions/221732/datetime-null-value