Casting of Nullable Enums

C

CKKwan

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?)

On the other hand, if it is not nullable, it doesn't request to cast
to (int)

E En = (E) Value;

Thanks in advance.
 
P

Pavel Minaev

CKKwan said:
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.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top