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

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.
 
S

Stoitcho Goutsev \(100\)

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.
 
N

Nicholas Paldino [.NET/C# MVP]

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.
 
T

TheSteph

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.
 
J

Jon Skeet [C# MVP]

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 :)
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top