Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the underlying value of an enum

Tags:

c#

.net

enums

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.

like image 279
George Mauer Avatar asked Sep 18 '08 21:09

George Mauer


People also ask

How do you find the value of an enum?

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.

What is the underlying type of an enum?

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.


2 Answers

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
    }    
like image 95
Andre Avatar answered Sep 28 '22 04:09

Andre


I believe Enum.GetValues() is what you're looking for.

like image 36
Andy Avatar answered Sep 28 '22 06:09

Andy