Monday, June 16, 2008

Fun with Casting

This is a .NET specific post. I ran into this interesting behavior the other day. It makes perfect sense, but I'd never thought about it before so I thought I'd share.

object o = 5.0;
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;

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.