22

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.

jason
  • 236,483
  • 35
  • 423
  • 525
iTSrAVIE
  • 846
  • 3
  • 12
  • 26

2 Answers2

63
DateTime? dt = (string1 == string2) ? (DateTime?)null
                                    : DateTime.Parse(txtbox.Text);
LukeH
  • 263,068
  • 57
  • 365
  • 409
0

you can do it like that:

DateTime ? dt = (string1 == string2) ? new Nullable <DateTime>(): (DateTime)(txtbox.Text);
fixagon
  • 5,506
  • 22
  • 26
  • You can't directly cast a `string` to a `DateTime`. You'll need to use the `Parse` method instead. http://msdn.microsoft.com/en-us/library/1k1skd40.aspx – LukeH Jun 02 '11 at 13:39