Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can't I cast boxed int to nullable decimal? [duplicate]

Tags:

c#

.net

Why there is InvalidCastException thrown? Can someone describe me this behavior?

object zero = 0;
decimal? dec = (decimal?)zero;
like image 458
Przemaas Avatar asked Dec 08 '22 06:12

Przemaas


1 Answers

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:

  1. Checking the object instance to make sure that it is a boxed value of the given value type.
  2. Copying the value from the instance into the value-type variable.

Edit: This linked article is worth pulling out of the comments. Thanks Rob Kennedy!

like image 107
jason Avatar answered Dec 17 '22 08:12

jason