public enum Foo : byte
{
BAR = 0x00,
BAZ = 0x01,
DERP = 0xFF
}
public void AppendAsHex(StringBuilder sb, byte b)
{
sb.AppendFormat("{0:X}", b);
}
Why does this demand an explicit cast?
Foo theDerp = Foo.DERP;
AppendAsHex(sb, (byte)theDerp); // Fine
AppendAsHex(sb, theDerp); // Compile Error
No loss of precision can occur. The method declares it only wants a byte, disregarding any enum goodness.
EDIT
This works fine if we trade the enum for a byte and make the function take another numeric type, eg:
public void AppendAsHex(StringBuilder sb, uint u)
{
sb.AppendFormat("{0:X}", u);
}
byte b = 21;
AppendAsHex(sb, b); // Fine
So, the compiler will promote a numeric type to a larger numeric type without any fuss, but demands a cast to do the same with an enum:byte to byte.
Clearly an enum:byte is not technically of Type byte, but surely the compiler could see it's of type System.Enum and check the type of the values contained in the enum?
While it makes perfect sense if using complex types the compiler may not be able to size up, in this case the compiler is fully aware of everything. I don't see how, if primitives can be promoted, the compiler would refuse to promote/cast something explicitly declared as a primitive.
It seems inconsistent to me and I'd like to understand it better.