471,330 Members | 1,851 Online
Bytes | Software Development & Data Engineering Community
Post +

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 471,330 software developers and data experts.

Casting of Nullable Enums

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.
Sep 1 '08 #1
1 7920
"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.

Sep 1 '08 #2

This discussion thread is closed

Replies have been disabled for this discussion.

Similar topics

3 posts views Thread by Matt | last post: by
1 post views Thread by Fei Li | last post: by
4 posts views Thread by DKode | last post: by
18 posts views Thread by Visual Systems AB \(Martin Arvidsson\) | last post: by
10 posts views Thread by Tyler Durden | last post: by
2 posts views Thread by John Smith | last post: by
4 posts views Thread by PokerMan | last post: by
5 posts views Thread by =?Utf-8?B?THVpZ2k=?= | last post: by
reply views Thread by rosydwin | last post: by

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.