Why there is InvalidCastException thrown? Can someone describe me this behavior?
object zero = 0;
decimal? dec = (decimal?)zero;
A boxed int
can only be unboxed to an int
. This, however, is legal:
object zero = 0;
decimal? dec = (decimal?)(int)zero;
See MSDN or the ECMA 334 C# spec for details. The key here is the following:
Unboxing is an explicit conversion from the type object to a value type or from an interface type to a value type that implements the interface. An unboxing operation consists of:
Edit: This linked article is worth pulling out of the comments. Thanks Rob Kennedy!
See this article http://msdn.microsoft.com/en-us/magazine/cc301569.aspx
Specifically "The common language runtime first ensures that the reference type variable is not null and that it refers to an object that is a boxed value of the desired value type. If either test fails, then an InvalidCastException exception is generated."
I think you are failing on the object of that value. I think the coversion to int works because that 0 literal will convert to an int and then an int converts to decimal.
If you do this it works
decimal? test=0;
object zero = test;
decimal? dec = (decimal?)zero;
But I think the "0" in your snippet is not a "decimal" type.
I am still not positive cause this gets the same exception.
int test=0;
object zero = test;
decimal? dec = (decimal?)zero;