"CKKwan" <ck****@my-deja.comwrote in message
news:d2**********************************@v16g2000 prc.googlegroups.com...
enum E = {a = 10, b = 10, c = 10};
object Value = 10;
E? En = (E?)(int?)Value;
Why do I need to caste it to (int?) before (E?)
Because the boxed value is of type int, and not of your enum type. When
unboxing, you always have to unbox to the precise type of the value; any
conversions are not considered. Similarly, you can't box a float, and then
unbox it straight to an int, even though you can normally cast a float to a
nint.
On the other hand, if it is not nullable, it doesn't request to cast
to (int)
E En = (E) Value;
The fact that it works is actually incorrect, and it's more of a deficiency
in the existing .NET implementation than anything else. According to both
the language spec and the CLR spec, it shouldn't work. A similar case is
with a boxed int unboxable to uint and vice versa, even though they're two
distinct types.