Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

cannot implicitly convert type System.DateTime? to System.DateTime

Tags:

c#

datetime

When I do the following I get:

    inv.RSV = pid.RSVDate

I get the following: cannot implicitly convert type System.DateTime? to System.DateTime.

In this case, inv.RSV is DateTime and pid.RSVDate is DateTime?

I tried the following but was not successful:

 if (pid.RSVDate != null)
 {                

    inv.RSV = pid.RSVDate != null ? pid.RSVDate : (DateTime?)null;
 }

If pid.RSVDate is null, I like to not assign inv.RSV anything in which case it will be null.

like image 757
Nate Pet Avatar asked Dec 05 '11 17:12

Nate Pet


2 Answers

DateTime can't be null. It's default is DateTime.MinValue.

What you want to do is the following:

if (pid.RSVDate.HasValue)
{
    inv.RSV = pid.RSVDate.Value;
}

Or, more succinctly:

inv.RSV = pid.RSVDate ?? DateTime.MinValue;
like image 111
Ahmad Mageed Avatar answered Nov 05 '22 02:11

Ahmad Mageed


You need to make the RSV property nullable too, or choose a default value for the case where RSVDate is null.

inv.RSV = pid.RSVDate ?? DateTime.MinValue;
like image 8
Thomas Levesque Avatar answered Nov 05 '22 02:11

Thomas Levesque