Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C#, cast variable to Enum.GetUnderlyingType

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.

like image 575
Aremyst Avatar asked May 07 '13 03:05

Aremyst


2 Answers

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)))
like image 194
Steven Wexler Avatar answered Sep 30 '22 10:09

Steven Wexler


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.

like image 36
David Cummins Avatar answered Sep 30 '22 12:09

David Cummins