Posts
58
Comments
399
Trackbacks
0
Casting value type to object and back to another value type...

This may be old news for other people, but new to me and I am trying to put in new stuff that I learned.  I wasn't aware of this, and after thinking about it, it does make sense (looking at it from how boxing/unboxing works), but I wished it had worked.

The following code will throw an InvalidCastException

 private void PassValue()

{

   float f = 5;

   double d = CastValue(f);

}

 

private double CastValue(object o)

{

   return (o is float) ? (double)o : double.NaN;

}

So would the following.

private void PassValue()

{

   int i = 5;

   object o = i;

   Int64 j = (Int64)o;

 

}

When .NET boxes a value type, it keeps the type with it, and any effort to cast it as something else will fail.  I was surprised with this; a consumer of my infrastructure project was telling about this exception where a piece of code was casting an object passed as a double.  He was passing a float.

Like I mentioned, after looking at it and thinking about it in terms of .NET boxing/unboxing, it makes sense.  I just wished it had worked.  I could've just used the Convert.ToDouble (or use IConvertible), but I wanted to make sure the passed value IS a numeric type.  If it's a string, or a byte for instance, I want to throw an exception.  Now I have to change my code so it checks for all possible numeric type and throw an exception if it's not.  Bummer...

posted on Monday, January 21, 2008 5:12 PM Print
Comments
No comments posted yet.

Post Comment

Title *
Name *
Email
Comment *