Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can enums return string instead of an integer? [duplicate]

Tags:

c#

enums

c#-4.0

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?

like image 591
Hakan Avatar asked Dec 07 '22 23:12

Hakan


2 Answers

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,
   ...
}
like image 106
Alexander Derck Avatar answered Jan 30 '23 09:01

Alexander Derck


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'
}
like image 37
pwas Avatar answered Jan 30 '23 08:01

pwas