Datetime is not nullable unless we declare it as DateTime?. Hence, DateTime when compared to NULL will always return false, but DateTime? can be NULL or have some value.
Interviews11 answers
Can DateTime be compared to null? Why or why not?
11 Answers
Munib ButtPosted Apr 28, 2020, 9:45 AM EDT
DateTime? ff=null;
if (ff==null)
{
}
siva bPosted Mar 13, 2019, 12:45 AM EDT
DateTime is a value type (structure) and has default value 1/1/0001 12:00:00 AM.
we can compare it with null but can not hold null as it is value type unless made it as nullable datatype.
DateTime? today = DateTime.Now;
today=null;
Bhanuprasad MitturiPosted Nov 20, 2018, 12:52 AM EST
DateTime is Rererence type .
So We can Instantiated it by the new operator.Generaly the null value is not
accespted by the type variable.But we can make it nullable in the example
DateTime? dt = null;
var d = dt?.ToString();
MessageBox.Show(d);
Laxmidhar SahooPosted Oct 31, 2018, 11:06 PM EDT
NO
Madan ShekarPosted Oct 31, 2018, 4:38 AM EDT
It can be compared but result will be False
VinayPosted Oct 29, 2018, 8:07 PM EDT
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.
Sreekanth ReddyPosted Oct 26, 2018, 3:51 AM EDT
Yes, If declare DateTime variable as nullable like DateTime? then we can compare it with null.
Vikas AgarwalPosted Oct 26, 2018, 3:41 AM EDT
And also to be noted if we compare with null it gives us false result because DateTime cannot understand what is null value and to which component of DateTime type it is actually being compared. So it is of no usage. I have given solution in my previous comment on how to deal with such situation.
Kapil GaurPosted Oct 26, 2018, 3:25 AM EDT
DateTime is by default not a nullable type. So it can never store null value. Only if you declare DateTime nullable by notation DateTime? then it can hold null value.
So I don't know what basically you want to perform. So suppose you want to do some assignment by checking whether the property has value or not for that you can use following.
If you are using DateTime then
DateTime dat = new DateTime();
if (dat==DateTime.MinValue)
{
//unassigned datetime
}
Or if you are using nullable DateTime then
DateTime? dat = null;
if (!dat.HasValue)
{
//unassigned
}
So answer to your question simply is that DateTime can never hold null value so cannot be compared. But there are ways by which we can understand if that particular property is having intended DateTime value or not.
Kapil GaurPosted Oct 26, 2018, 3:21 AM EDT
DateTime CAN be compared to null; It cannot hold null value, thus the comparison will always be false.
Sandeep SoniPosted Oct 24, 2018, 8:15 PM EDT







