Click here to Skip to main content
15,890,512 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
C#
DateTime? someDate = null;

someDate = (bool)CheckBoxExpired.IsChecked ? DateTime.Now : null;

if ((bool)CheckBoxExpired.IsChecked) someDate = DateTime.Now; else someDate = null;


The second line of code gives the following error:

type of conditional expression cannot be determined because there is no implicit conversion between DateTime and Null

The third line is ok.

In my opinion both lines of code are the same, but why do I get an error on the first one?
Posted

Please check below link. It has very clearly explained reason behind this.

http://stackoverflow.com/questions/295833/nullable-type-issue-with-conditional-operator[^]
 
Share this answer
 
Comments
Praveen Kumar Upadhyay 13-Mar-15 3:34am    
It's because in a ternary operator, the two values must be the same type.
Jan Bakker 13-Mar-15 3:36am    
Now it's clear to me.
Thanks.
Maciej Los 13-Mar-15 3:37am    
+5!
Praveen Kumar Upadhyay 13-Mar-15 3:39am    
Thanks Maciej, actual credit goes to the guys who has posted this solution. Even I was knowing this answer, but he has explained very proper.
Jan Bakker 13-Mar-15 3:42am    
The actual answer to my question is:
It's because in a ternary operator, the two values must be the same type.
Short and clear answer, so 5+
Try this:
? DateTime.Now : (DateTime?) null
 
Share this answer
 
v2
Comments
Jan Bakker 13-Mar-15 3:28am    
That works, but why is that necessary?
It's not necessary in the the other line of code.
Peter Leow 13-Mar-15 3:34am    
http://www.dotnetperls.com/nullable-datetime
Maciej Los 13-Mar-15 3:37am    
+5
Peter Leow 13-Mar-15 4:27am    
Thank you, Maciej.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900