Necati Hakan Erdogan Necati Hakan Erdogan - 1 year ago 71
C# Question

Can enums return string instead of an integer?

I want my enums to return string values. Not the Enum Description, they must be returning a string value, instead of an int. The code sample below is exactly what in my mind, but obviously doesn't compile.

public enum TransactionType
{
CreditCard = "C",
DebitCard = "D",
CreditCardAuthenticationWithAuthorization = "CA",
DebitCardAuthenticationWithAuthorization = "DA"
}


Any ideas?

Answer Source

You can't, what you can do is create a static class that "acts" a bit like an enum with string values:

public static class TransactionType
{
   public const string CreditCard = "C";
   ...
}

You can access them the same way then:

string creditCardValue = TransactionType.CreditCard;

Another option would be to work with the DescriptionAttribute in System.ComponentModel namespace, but then your enums still will have underlying numeric values, so maybe that's not entirely what you need.

Example:

public enum TransactionType
{
   [Description("C")]
   CreditCard,
   ...
}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download