views:

74

answers:

1

The tooltip displayed for Convert.ToDateTime() says that it always throws System.InvalidCastException. Why?

+4  A: 

You cannot cast something like a short (or bool or various other datatypes) to DateTime, so it makes sense for that to always throw. If, however, you try to convert something that could sensibly be converted to a DateTime, then it doesn’t:

example screenshot showing the tooltip for two of the Convert.ToDateTime() overloads

Timwi
+1 for finding it. Makes a person wonder why the overload is provided if it only throws an exception. Seems unreasonable.
John K
@jdk: My guess is because it prevents boxing. If the overload wasn’t there, then `ToDateTime(object)` would take over and throw the same exception. Even if `ToDateTime(object)` were changed to `ToDateTime(IConvertible)`, which apparently it requires, it would still take over because all the primitive types implement that interface...
Timwi
@jdk: Out of curiosity, would you explain to me how you discovered my answer so quickly? I don’t think the site sends out e-mails so soon, and nobody favourited this question, so what did you do? Did you keep reloading this page or something? Or did you and another user just happen to independently stumble upon my answer 8 minutes after it was posted?
Timwi
@Timwi: Just saw the question float by as a new one and thought it looked interesting. At one point you had two different answers being developed.
John K
Yeah, I deleted the other one because it’s obsolete now.
Timwi