Cannot implicitly convert the type to System.DateTime? to System.DateTime

When I do the following, I get:

inv.RSV = pid.RSVDate 

I get the following: can I not implicitly convert the System.DateTime type? 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 don't like to assign inv.RSV to anything, in which case it will be null.

+6
source share
5 answers

DateTime cannot be null. The default is DateTime.MinValue .

What you want to do is the following:

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

Or, more briefly:

 inv.RSV = pid.RSVDate ?? DateTime.MinValue; 
+15
source

You need to set the RSV property to nullable or choose the default value for the case when RSVDate is null.

 inv.RSV = pid.RSVDate ?? DateTime.MinValue; 
+8
source

Since inv.RSV is not a nullable field, it cannot be NULL. When you initialize your object, it is invSRSV by default for an empty DateTime, just as you would if you said

 inv.RSV = new DateTime() 

So, if you want to set inv.RSV to pid.RSV, if it is not NULL, or DateTime is null by default, do the following:

 inv.RSV = pid.RSVDate.GetValueOrDefault() 
+2
source

if the one that is assigned as DateTime and the one that is assigned is DateTime? , you can use

 int.RSV = pid.RSVDate.GetValueOrDefault(); 

This supports overloading, which allows you to specify a default value if the default value for DateTime not ideal.

If pid.RSVDate is null, I don't like to assign inv.RSV to anything, case it will be null.

int.RSV will not be null, as you said, DateTime , not a type with a null value. If it is never assigned by you, it will have a default value for this type, which is equal to DateTime.MinValue , or January 1, 0001.

inv.RSV was zero to begin with. How can I say do not update it, there is no value for pid.RSVDate

Again, this simply cannot be, given your description of the property. However, if you don't want to update inv.RSV , if pid.RSVDate is null (and you just mix your words), then you just write an if check around the destination.

 if (pid.RSVDate != null) { inv.RSV = pid.RSVDate.Value; } 
+1
source

pid.RSVDate has the ability to be null , whereas inv.RSV does not, so what happens if RSVDate is null ?

You need to check if the value is null before -

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

But what would be the value of inv.RSV if RSVDate is NULL? Is there always a date in this property? If so, can you use the ?? operator to assign a default value if you want.

 pid.RSV = pid.RSVDate ?? myDefaultDateTime; 
0
source

Source: https://habr.com/ru/post/903128/


All Articles