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>
Try this one:
DateTime? date = String.IsNullOrEmpty(textBoxDate.Text) ?
null as DateTime? : DateTime.Parse(textBoxDate.Text);
(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 RHSDateTime 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With