My statement started out as this:
Object.NullableDt = (formCollection["date_input"] == null || formCollection["date_input"] == String.Empty ? null : DateTime.Parse(formCollection["date_input"].ToString());
Simple and straight forward, right? Apparently not! I got the ol' red underline in Visual Studio 2012 and (of course) my code wouldn't compile. The error was "Error 20" "Type of conditional expression cannot be determined because there is no implicit conversion between <null> and System.DateTime."
Now, my personal opinion on this is that the compiler fails here and in a pretty epic way but, opinions aside, the suggested fix is easy to implement and works like a charm. Here's my original statement, modified to appease the unintelligent compiler:This doesn't work because the compiler will not insert an implicit conversion on both sides at once.
You want the compiler to convert aDateTime
value toDateTime?
on one side, andnull
toDateTime?
on the other side.
This cannot happen.
If you explicitly convert either half toDateTime?
, the other half will implicitly convert too.
Object.NullableDt = (formCollection["date_input"] == null || formCollection["date_input"] == String.Empty ? new DateTime?() : DateTime.Parse(formCollection["date_input"].ToString());
Note that what was once
null
is now new DateTime?()
thus fulfilling the compiler's odd need to have an explicit type on one side of the statement. This could also be achieved by casting the right side of the statement to the appropriate type.So, there you have it; Solving compiler stupidity with a few extra keystrokes. :-)
No comments:
Post a Comment