object o = 5.0;
int i = (int)o;
int i = (int)o;
That code will bomb out with a run time exception complaining about an invalid cast.
object o = 5.0;
int i = (int)(double)o;
int i = (int)(double)o;
That code will run just fine.
What's happening is the meaning of the cast is different. In the first case I'm saying that I expected there to be an int in the object. There isn't, it's a double. So it blows up. In the second case I'm saying that I expected there to be a double in the object and that I want it to truncate the double into an int. It's slightly unexpected because the same syntax means two different things depending on the types it's acting on.
No comments:
Post a Comment
Note: Only a member of this blog may post a comment.