I have the following enum declared:
public enum TransactionTypeCode { Shipment = 'S', Receipt = 'R' }
How do I get the value 'S' from a TransactionTypeCode.Shipment or 'R' from TransactionTypeCode.Receipt ?
Simply doing TransactionTypeCode.ToString() gives a string of the Enum name "Shipment" or "Receipt" so it doesn't cut the mustard.
To get the value of enum we can simply typecast it to its type. In the first example, the default type is int so we have to typecast it to int. Also, we can get the string value of that enum by using the ToString() method as below.
Each enum type has a corresponding integral type called the underlying type of the enum type. This underlying type shall be able to represent all the enumerator values defined in the enumeration. If the enum_base is present, it explicitly declares the underlying type.
You have to check the underlying type of the enumeration and then convert to a proper type:
public enum SuperTasks : int
{
Sleep = 5,
Walk = 7,
Run = 9
}
private void btnTestEnumWithReflection_Click(object sender, EventArgs e)
{
SuperTasks task = SuperTasks.Walk;
Type underlyingType = Enum.GetUnderlyingType(task.GetType());
object value = Convert.ChangeType(task, underlyingType); // x will be int
}
I believe Enum.GetValues() is what you're looking for.
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