views:

52

answers:

4

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>

A: 

null can be any reference type, you have to cast it or use the as operator:

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

Assuming that textBoxDate can be converted implicitely to Datetime?, which is doubtfull...

Philippe
+2  A: 

(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.

Jon Skeet
+2  A: 

Try this one:

DateTime? date = String.IsNullOrEmpty(textBoxDate.Text) ? 
null as DateTime? : DateTime.Parse(textBoxDate.Text);
Bashir Magomedov
A: 

Well, I don't know what your textBoxDate.Text class is like, but I was able to get this to work, compile, and return an expected result.

    TextBox textBoxDate = new TextBox();
    textBoxDate.Text = string.Empty;
    DateTime? date = (textBoxDate.Text != "") ? (DateTime?)DateTime.Parse(textBoxDate.Text) : null;

I think the explicit cast to (DateTime?) is what you need

Matthew Ruston