The simplest way to get an enum’s int value is by casting it to an int. Here’s an example:
int val= (int)EmployeeType.Coder;
Console.WriteLine($"{employeeType}={val}");
public enum EmployeeType
{
None = 0,
Coder = 50,
QA = 100,
Designer = 200
}
Code language: C# (cs)
This outputs the following:
Coder=50
Code language: plaintext (plaintext)
When the enum is generic (of type ‘Enum’)
You can’t cast a generic ‘Enum’ to int, otherwise you get a compiler error (CS0030 Cannot convert type ‘System.Enum’ to ‘int’). Use Convert.Int32() instead. Here’s an example:
Enum enumObject = EmployeeType.QA;
int val = Convert.ToInt32(enumObject);
Console.WriteLine($"{enumObject}={val}");
Code language: C# (cs)
This outputs the following:
QA=100
Code language: plaintext (plaintext)
Note: Double casting the enum – (int)(object)enumObject – works too, but Convert.ToInt32() is more intuitive.
When the enum’s underlying type isn’t Int32
By default, enums have an underlying type of int (Int32), but they can be defined with any integer type (byte, short, int, long, and unsigned equivalents). To get the enum’s integer value, you can cast it to its underlying type (as shown up above).
But don’t cast an enum to a specific type unless you know its underlying type for sure. Otherwise it can result in getting the incorrect value. Instead, you can use GetTypeCode() to get its underlying type and then use Convert.ChangeType() to convert it to the type. Here’s an example:
Enum enumObject = EmployeeType.Coder;
object val = Convert.ChangeType(enumObject, enumObject.GetTypeCode());
Console.WriteLine($"{enumObject}={val}");
//Defining the enum with underlying type of byte (unsigned 8-bit integer with values from 0-255)
public enum EmployeeType : byte
{
None = 0,
Coder = 1,
QA = 2,
Designer = 255
}
Code language: C# (cs)
This outputs:
Coder=1
Code language: plaintext (plaintext)