Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing null values in single line Conditional

Just a fictional code, but why this won't work? (as the date variable is nullable)

DateTime? date = textBoxDate.Text != "" ? textBoxDate.Text : null;

The error is "There is no explicit conversion between System.DateTime and <null>

like image 370
Vitor Reis Avatar asked Aug 06 '26 21:08

Vitor Reis


2 Answers

Try this one:

DateTime? date = String.IsNullOrEmpty(textBoxDate.Text) ? 
null as DateTime? : DateTime.Parse(textBoxDate.Text);
like image 180
Bashir Magomedov Avatar answered Aug 08 '26 09:08

Bashir Magomedov


(I'm assuming that in reality you've got a conditional which makes rather more sense - Text is presumably a string property, and it doesn't make much sense to assign that to a DateTime? variable.)

The compiler doesn't know the type of the conditional expression. It doesn't take any account of the fact that there's an assignment to a DateTime? variable - it's just trying to find the right type.

Now the type of the expression has to be either the type of the LHS, or the type of the RHS... but:

  • null doesn't have a type, so it can't be the type of the RHS
  • There's no conversion from DateTime to null so it can't be the type of the LHS either.

The simplest way to fix this is to give the RHS a real type, so any of:

default(DateTime?)
(DateTime?) null
new DateTime?()

You could of course make the LHS of type DateTime? instead.

like image 35
Jon Skeet Avatar answered Aug 08 '26 09:08

Jon Skeet



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!