I was working with a small piece of code in Sharepoint, that goes like this:
int? do_ = (int?)re["mi"]; // consider "re" a dictionary<string, object>;
The expression to the right of the equal sign evaluates to a Double
. To make double
sure, I double
-checked it (:D) in the watch window. And yeah, it's a System.Double
, in and out.
However, that line throws an exception:
Specified cast is not valid.
I was about to make a dent on my desk with my forehead when it dawned on me that yes, you can cast double to int, though losing the non-integer part of the value (which is actually intended in my case). I learned this in my first days of programming, before the world moved on.
So to be even more sure, I created another solution, a simple console app. I put this code into it:
double dragon = 2.0;
int? i = (int?)dragon;
And it works, just as expected.
Why would it work in one setting but fail in the other one?