I agree with Jon that for enums, you can unbox an enum to the underlying
type of the enum directly, as long as the variable has the same type of
underlying type of the enum.
Using following code snippet:
using System;
enum Foo : long
{
Bar, Baz
}
class Test
{
static void Main()
{
object boxedEnum = Foo.Bar;
int i1 = (int)(Foo)boxedEnum;
int i2 = (int)boxedEnum;
}
}
The i1 works correctly while i2 fails with InvalidCastException.
i1 works because we first unbox to the enum; then do a cast from long to
int which is ok.
i2 doesn't work because we cannot unbox a boxed long value to int.
Internally, here's exactly what happens when a boxed value type instance is
unboxed:
1. If the variable containing the reference to the boxed value type
instance is null, a NullReferenceException is thrown.
2. If the reference doesn't refer to an object that is boxed instance of
the desired value type, an InvalidCastException is thrown.
So I guess Nicholas's suggestion to unbox to the enum type first is more
safe if you don't know the underlying type of enum.
Here's some background information about enum:
======
When an enumerated type is compiled, the compiler turns each symbol into a
constant field of the type. For example:
internal struct Color : System.Enum {
public const Color White = (Color) 0;
public const Color Black = (Color) 1;
// Below is a public instance field containing a Color variable's
value
// You cannot write code that references this instance field
directly
public Int32 value__;
}
Note: the compiler won't actually compile this code because it forbids you
from defining a type derived from the special System.Enum type. However,
this pseudo-type definition shows you waht's happening internally.
Basically, an enumerated type is just a structure with a bunch of constant
fields defined in it and one instance field.
Every enumerated type has an underlying type, which can be a byte, sbyte,
short, ushort, int (the most common and default type), uint, long, or
ulong.
The compiler treats enumerated types as primitive types. As such, you can
use many of the familiar operators (==, !=, <, >, <=, >=, +, -, ^, &, |, ~,
++, and --) to manipulate enumerated type instances. All of these operators
actually work on the value__ instance field inside each enumerated type
instance.
======
Regards,
Walter Wang (
[email protected], remove 'online.')
Microsoft Online Community Support
==================================================
When responding to posts, please "Reply to Group" via your newsreader so
that others may learn and benefit from your issue.
==================================================
This posting is provided "AS IS" with no warranties, and confers no rights.