Assigning null/Nullable to DateTime in Ternary Operation

懵懂的女人 提交于 2019-12-21 07:08:43

问题


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.


回答1:


DateTime? dt = (string1 == string2) ? (DateTime?)null
                                    : DateTime.Parse(txtbox.Text);



回答2:


you can do it like that:

DateTime ? dt = (string1 == string2) ? new Nullable <DateTime>(): (DateTime)(txtbox.Text);


来源:https://stackoverflow.com/questions/6215199/assigning-null-nullable-to-datetime-in-ternary-operation

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!