Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

There is no implicit conversion between null and datetime [duplicate]

Tags:

c#

Following code read a piece data from given DataRow(modelValue) and parse it to a nullable DateTime instance.

Question: Please see the code sections under L1 & L2 where both are technically equal (If i am not making any schoolboy error). However, L1 works as expected but not L2. I am getting

there is no implicit conversion between null and datetime

when I execute the code under L2. Can someone advise me ?

        DateTime? CallBack;

        var callBackDate = modelValue["CallBack"] == DBNull.Value ? null : modelValue["CallBack"].ToString();
        //Parsing
        DateTime cdate;
        if (!DateTime.TryParse(callBackDate, out cdate))
            cdate = DateTime.MinValue;


        //L1
        if (cdate==DateTime.MinValue)
            CallBack = null;
        else
           CallBack = cdate.Date;

       //L2  
       CallBack = cdate == DateTime.MinValue?null:cdate.Date;
like image 475
Sreejith Nair Avatar asked Sep 07 '25 15:09

Sreejith Nair


1 Answers

You need to tell the compiler that the null should be treated as DateTime?. Otherwise the compiler doesn't know what type null is.

CallBack = cdate == DateTime.MinValue ? (DateTime?)null : cdate.Date;

like image 162
Jakub Konecki Avatar answered Sep 09 '25 07:09

Jakub Konecki