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?
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 nullable DateTime, like this:
DateTime? MyNullableDate;
Or the longer form:
Nullable<DateTime> MyNullableDate;
I'd consider using a nullable types.
DateTime? myDate instead of DateTime myDate;
If you're using .NET 2.0 you can use the nullable type:
DateTime? dt = null;
or
Nullable<DateTime> dt = null;
then later:
dt = new DateTime();
And you can check the value with:
if (dt.ContainsValue)
{
// Do something with dt.Value
}
Or you can use it like:
DateTime dt2 = dt ?? DateTime.MinValue;
You can read more here:
http://msdn.microsoft.com/en-us/library/b3h38hb0.aspx
You can use a nullable class.
DateTime? date = new DateTime?();
You can use a nullable DateTime for this.
Nullable<DateTime> myDateTime;
or the same thing written like this:
DateTime? myDateTime;
I always set the time to DateTime.MinValue
. This way I do not get any NullErrorException and I can compare it to a date that I know isn't set.
You can set the DateTime to Nullable. By default DateTime is not nullable. You can make it nullable in a couple of ways. Using a question mark after the type DateTime? myTime or using the generic style Nullable. I have added a couple of links on msdn.
myclass.MyNullableDateTime = (drOrder["Field1"] == DBNull.Value) ? (DateTime?)null : ((DateTime)drOrder["Field1"]);