Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

DateTime "null" value

Tags:

c#

datetime

null

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?

like image 442
Mats Avatar asked Oct 21 '08 12:10

Mats


People also ask

What is the null value of DateTime?

DateTime is a Value Type like int, double etc. so there is no way to assigned a null value.

Can DateTime be null?

DateTime CAN be compared to null; It cannot hold null value, thus the comparison will always be false. DateTime is a "Value Type". Basically a "value type" can't set to NULL. But by making them to "Nullable" type, We can set to null.

Can we assign null to DateTime in C#?

Using the DateTime nullable type, you can assign the null literal to the DateTime type.


1 Answers

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 
like image 185
Joel Coehoorn Avatar answered Oct 06 '22 00:10

Joel Coehoorn