Unsafe C# - Converting Enums to Bytes
Whilst working on my Cards project I needed to convert enum values into bytes. The enums in question have ints as their underlying types rather than bytes (even though I could make the underlying type byte everyone pretty much expects all enums will have ints as their underlying type so I've stuck with that) so there will be a (very small!) amount of work to convert them to bytes. I was wondering, purely out of interest as its a silly thing to be doing, if I could do anything quicker using unsafe code. If I could grab the bytes for the underlying int I could simply return the first one and bypass any checks the runtime might do.
To test I used the ConsoleColor enum and came up with the following equivalent functions:
private static byte SafeConvert(ConsoleColor value)
{
return (byte) value;
}
private unsafe static byte UnsafeConvert(ConsoleColor value)
{
return *(byte*) &value;
}
Ran some timing tests and there was no detectable difference... To be expected really - its a very simple conversion after all.
Full code of the timing application can be found here.