Possible Duplicate:
Type result with conditional operator in C#
I was just working on an a pop-up for modifying a user, when I ran into the following issue while attempting to modify the user’s Date of Death :
In this scenario, the property Death for the user is a DateTime? (Nullable Date Time).
user.Death = (model.Death != null) ? DateTime.Parse(model.Death) : null;
So I figured that I would be able to simply check if the value contained in the model (model.Death is a string) contained a value, I would set the date that value, otherwise I would set it to null, as demonstrated above.
However, I was unable to use this syntax, as it would not allow me to explicitly set user.Death to null, using the ternary operator, although user.Death = null worked just fine.
Solution used :
Replaced : null with : new Nullable<DateTime>()
I guess I am just wondering, why was I unable to explicitly set a Nullable DateTime property to null using a ternary operator?
This doesn’t work because the compiler will not insert an implicit conversion on both sides at once.
You want the compiler to convert a
DateTimevalue toDateTime?on one side, andnulltoDateTime?on the other side.This cannot happen.
If you explicitly convert either half to
DateTime?, the other half will implicitly convert too.