Given a generic parameter TEnum which always will be an enum type, is there any way to cast from TEnum to int without boxing/unboxing?
See this example code. This will box/unbox the value unnecessarily.
private int Foo<TEnum>(TEnum value)
where TEnum : struct // C# does not allow enum constraint
{
return (int) (ValueType) value;
}
The above C# is release-mode compiled to the following IL (note boxing and unboxing opcodes):
.method public hidebysig instance int32 Foo<valuetype
.ctor ([mscorlib]System.ValueType) TEnum>(!!TEnum 'value') cil managed
{
.maxstack 8
IL_0000: ldarg.1
IL_0001: box !!TEnum
IL_0006: unbox.any [mscorlib]System.Int32
IL_000b: ret
}
Enum conversion has been treated extensively on SO, but I could not find a discussion addressing this specific case.
I guess you can always use System.Reflection.Emit to create a dynamic method and emit the instructions that do this without boxing, although it might be unverifiable.
Here is a simplest and fastest way.
(with a little restriction. :-) )
Restriction:
This works in Mono. (ex. Unity3D)
More information about Unity3D:
ErikE's CastTo class is a really neat way to solve this problem.
BUT it can't be used as is in Unity3D
First, it have to be fixed like below.
(because that the mono compiler can't compile the original code)
Second, ErikE's code can't be used in AOT platform.
So, my code is the best solution for Mono.
To commenter 'Kristof':
I am sorry that I didn't write all the details.