c# - DateTime "null" value

ID : 10106

viewed : 22

Tags : c#datetimenullc#

Top 5 Answer for c# - DateTime "null" value

vote vote

98

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; 

And, finally, there's a built in way to reference the default of any type. This returns null for reference types, but for our DateTime example it will return the same as DateTime.MinValue:

default(DateTime) 

or, in more recent versions of C#,

default 
vote vote

82

If you're using .NET 2.0 (or later) 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.HasValue) {   // 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

vote vote

74

DateTime? MyDateTime{get;set;}

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

64

Following way works as well

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

Please note that property PublishDate should be DateTime?

vote vote

56

I'd consider using a nullable types.

DateTime? myDate instead of DateTime myDate.

Top 3 video Explaining c# - DateTime "null" value

Related QUESTION?