Problem setting DateTime? to zero using the ternary operator

Possible duplicate:
Enter the result with a conditional statement in C #

I was just working on a popup to change the user when I encountered the following problem when trying to change the user of Date of Death:

In this case, the property Deathfor the user is DateTime?(Nullable Date Time).

user.Death = (model.Death != null) ? DateTime.Parse(model.Death) : null;

So, I realized that I can just check if the value contained in the model (model.Death is a string) contains a value, I would set a date whose value, otherwise I would set it to zero, as shown above.

However, I was not able to use this syntax because it would not allow me to explicitly set user.Deathto null using the ternary operator, although it user.Death = nullworked just fine.

Solution Used:

Replace : nullwith: new Nullable<DateTime>()

I think I'm just wondering why I couldn't explicitly set the Nullable DateTime property to null using the ternary operator?

+3
source share
2 answers

This does not work, because the compiler will not insert the implicit conversion on both sides at once.

You want the compiler to convert the value DateTimein DateTime?the one hand, and null- DateTime?on the other hand.
It cannot be.

DateTime?, .

+5

, user.Death = null , Death NULL.

, "DateTime? Death = null" , "DateTime death = null" .

0

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


All Articles