Assigning null/Nullable to DateTime in Ternary Operation

15,680
DateTime? dt = (string1 == string2) ? (DateTime?)null
                                    : DateTime.Parse(txtbox.Text);
Share:
15,680

Related videos on Youtube

iTSrAVIE
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, 2020

Comments

  • iTSrAVIE
    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 to DateTime.

    So, I have to declare a Nullable<DateTime> nullable variable and replace null with nullable.

    I do not want to use if-statement and I want to do this in one line.

    Also, Can I use operator ?? here.

  • LukeH
    LukeH about 13 years
    You can't directly cast a string to a DateTime. You'll need to use the Parse method instead. msdn.microsoft.com/en-us/library/1k1skd40.aspx