Suppose I have enum, which underlying type is byte:
enum EmpType : byte
{
Manager = 1,
Worker = 2,
}
Can I cast some int literal to underlying type of this enum(byte in this case) ?
Something like this doesn't work (Error: "; expected"):
byte x = (Enum.GetUnderlyingType(typeof(EmpType)))15;
Can I cast to underlying type without explicitly writing (byte)15 ?
Thanks.
I think the following will work. But I'm not sure it will get you the desired behavior in all cases.
var x = Convert.ChangeType(15, Enum.GetUnderlyingType(typeof(EmpType)))
I'm not entirely sure what you're trying to do. Below is a related question about casting ints to enums and vice-versa, the same applies to byte in this case.
Is it possible to cast integer to enum?
If you want to detect the underlying type at run-time... it seems awkward and a lot of work. You could just do a case statement based upon the name of the underlying type. I'm not sure what good it would do you due to type safety concerns.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With