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!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With