Assigning null/Nullable to DateTime in Ternary Operation
15,680
DateTime? dt = (string1 == string2) ? (DateTime?)null
: DateTime.Parse(txtbox.Text);
Related videos on Youtube
![iTSrAVIE](https://i.stack.imgur.com/torK7.gif?s=256&g=1)
Author by
iTSrAVIE
Developer with 8+ years experience in .Net & Web Technologies. All the Best in Development. / / The best thing about a boolean is even if you are wrong, you are only off by a bit. Stay Positive!**
Updated on February 13, 2020Comments
-
iTSrAVIE over 4 years
I have a statement like
DateTime ? dt = (string1 == string2) ? null; (DateTime)(txtbox.Text);
which I cannot compile. Reason is :
null
cannot be assigned toDateTime
.So, I have to declare a
Nullable<DateTime> nullable
variable and replacenull
withnullable
.I do not want to use
if
-statement and I want to do this in one line.Also, Can I use operator
??
here. -
LukeH about 13 yearsYou can't directly cast a
string
to aDateTime
. You'll need to use theParse
method instead. msdn.microsoft.com/en-us/library/1k1skd40.aspx