5

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?

Pecheneg
  • 768
  • 3
  • 11
  • 27

2 Answers2

12

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,
   ...
}
Alexander Derck
  • 13,818
  • 5
  • 54
  • 76
  • About your edited answer, I discovered that solution too. But I want it to look just like an enum to the developer who's gonna use my API. I think on the second solution you need to access differently. – Pecheneg Mar 04 '16 at 09:41
  • @NecatiHakanErdogan Yes, I think there's no other way to access them than to use some reflection. It's really inconvenient to get the descriptions. – Alexander Derck Mar 04 '16 at 09:42
3

No, there is no way. You can choose between int, long, byte, short - generally numeric types.

You can do "some cheat", only for char values (because char is implicity casted to int):

public enum MyEnum
{
   Value = 'a'
}
pwas
  • 3,225
  • 18
  • 40