R
Richard Blewett [DevelopMentor]
Dale,
Consider this code:
class App
{
static void Main(string[] args)
{
Foo f = Foo.One;
int i = (int)f;
}
}
enum Foo
{
One,
Two
}
if you look at the IL for Main you see:
.method private hidebysig static void Main(string[] args) cil managed
{
.entrypoint
// Code size 5 (0x5)
.maxstack 1
.locals init ([0] valuetype Foo f,
[1] int32 i)
IL_0000: ldc.i4.0
IL_0001: stloc.0
IL_0002: ldloc.0
IL_0003: stloc.1
IL_0004: ret
} // end of method App::Main
Notice there is no unbox instruction. So your assertion that the "cast" is actually an unbox operation is incorrect. The cast operator is abused in several situations. Its used for type coercion of reference types; its used for numeric conversion of value types and its used for boxing and unboxing. The enum is a value type with an associated numeric value. This is held in the value__ member of the enum and is typed to the type after the colon in the enum definition (or int32 if its omitted).
Regards
Richard Blewett - DevelopMentor
http://www.dotnetconsult.co.uk/weblog
http://www.dotnetconsult.co.uk
There is no value type of enum. There is an underlying TypeCode that is
used for integral representation of the enum. To get the value type, you
must unbox it. If it were already an int, it wouldn't be necessary to cast
an int as an int. But if you box an int, it is necessary to unbox to get
back to the int. The syntax for unboxing is, coincidentally, the same as
the syntax for an explicit cast.
Consider this code:
class App
{
static void Main(string[] args)
{
Foo f = Foo.One;
int i = (int)f;
}
}
enum Foo
{
One,
Two
}
if you look at the IL for Main you see:
.method private hidebysig static void Main(string[] args) cil managed
{
.entrypoint
// Code size 5 (0x5)
.maxstack 1
.locals init ([0] valuetype Foo f,
[1] int32 i)
IL_0000: ldc.i4.0
IL_0001: stloc.0
IL_0002: ldloc.0
IL_0003: stloc.1
IL_0004: ret
} // end of method App::Main
Notice there is no unbox instruction. So your assertion that the "cast" is actually an unbox operation is incorrect. The cast operator is abused in several situations. Its used for type coercion of reference types; its used for numeric conversion of value types and its used for boxing and unboxing. The enum is a value type with an associated numeric value. This is held in the value__ member of the enum and is typed to the type after the colon in the enum definition (or int32 if its omitted).
Regards
Richard Blewett - DevelopMentor
http://www.dotnetconsult.co.uk/weblog
http://www.dotnetconsult.co.uk
There is no value type of enum. There is an underlying TypeCode that is
used for integral representation of the enum. To get the value type, you
must unbox it. If it were already an int, it wouldn't be necessary to cast
an int as an int. But if you box an int, it is necessary to unbox to get
back to the int. The syntax for unboxing is, coincidentally, the same as
the syntax for an explicit cast.