Object/Decimal cast exception... Bug ? or is it me ?

  • Thread starter Thread starter TheSteph
  • Start date Start date
T

TheSteph

Why do I get an exception "The specified cast is not valid" ??? Is that a
bug or do I miss something ?


object DecimalObject = 1;
decimal TmpDecimal;
TmpDecimal = (decimal)DecimalObject;



Steph.
 
It is not a bug.
You can unbox value type only to the exact type of the object.

They way you box the value you don't get decimal boxed object

the following code works:

object DecimalObject = 1m;
decimal TmpDecimal;
TmpDecimal = (decimal)DecimalObject;

Note the 'm' sufix after the 1 that instructs the compiler that the litteral
constant is a decimal number.
 
You could also do this:

object DecimalObject = 1;
decimal TmpDecimal = (decimal)(int) DecimalObject;

Not clean, but it is possible.

If you have a boxed instance, it is better to use the Convert class
instead, so that you can avoid having to "know" what is in the boxed
instance.

Hope this helps.
 
Thanks !!!

In fact I didn't know that : "You can unbox value type only to the exact
type of the object".... so the bug was in my brain ;-)

Steph.
 
Stoitcho Goutsev (100) said:
It is not a bug.
You can unbox value type only to the exact type of the object.

There's one exception to this: enums. You can unbox a boxed enum value
to the underlying type of the enum, or to any other enum with the same
underlying type. Similarly you can unbox a boxed value of an integer
type to any enum with that type as the underlying type.

Oh, and the C# and CLI specs currently don't spell this out properly.

See, I knew that tidbit of useless information would come in handy one
day :)
 
Back
Top