tags:

views:

838

answers:

6

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.

+1  A: 

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

Andy
+2  A: 

Try this:

string value = (string)TransactionTypeCode.Shipment;
J D OConal
Actually its a little more complex, I copied the code wrong from my sample, you cannot have strings for values in an enum. so the full answer would be ((char)instance.Shipment),ToString()
George Mauer
A: 

Look into the Enumeration class (Enumeration.toObject) I believe....

Adam Driscoll
+1  A: 

This is how I generally set up my enums:

public enum TransactionTypeCode {

 Shipment("S"),Receipt ("R");

private final String val;

TransactionTypeCode(String val){
 this.val = val;
}

public String getTypeCode(){
  return val;
}

}

System.out.println(TransactionTypeCode.Shipment.getTypeCode());

oneBelizean
A: 

I was Searching For That and i get the Solution Use the Convert Class int value = Convert.ToInt32(TransactionTypeCode.Shipment);

see how it easy

+2  A: 

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
    }    
Andre
I suppose if you don't know the underlying type of the enum this would be the way to do it. But how you would ever end up in that situation is beyond me.
George Mauer
+1 This is the last step I needed to automatically (through reflection) create my SP parameter-value list from an entity object. I can't save the enum to the database, so I'm saving the underlying value.
jimr