I have an IDataRecord reader that I’m retrieving a decimal from as follows:
decimal d = (decimal)reader[0];
For some reason this throws an invalid cast exception saying that the “Specified cast is not valid.”
When I do reader[0].GetType() it tells me that it is an Int32. As far as I know, this shouldn’t be a problem….
I’ve tested this out by this snippet which works just fine.
int i = 3750;
decimal d = (decimal)i;
This has left me scratching my head wondering why it is failing to unbox the int contained in the reader as a decimal.
Does anyone know why this might be occurring? Is there something subtle I’m missing?
You can only unbox a value type to its original type (and the nullable version of that type).
By the way, this is valid (just a shorthand for your two line version):
For the reason behind this read this Eric Lippert’s blog entry: Representation and Identity
Personally, I categorize things done by cast syntax into four different types of operation (they all have different IL instructions):
boxIL instruction) and unboxing (unboxIL instruction)dynamic_cast<Type>in C++, usescastclassIL instruction to verify)static_cast<Type>in C++, there are plenty of IL instructions for different types of casts between primitive types)op_XXXmethod).