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 betwee开发者_如何学运维n 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 RHS- There's no conversion from
DateTime
tonull
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.
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...
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
its easy you just quit the initial cast datetime ? == type not null values permit, datetime == with out the ? permit null values
DateTime date = textBoxDate.Text != "" ? textBoxDate.Text : null;
精彩评论