Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating enums having Key Value as string

Tags:

c#

enums

I know following syntax is possible with enum, and one can get value by parsing it in int or char.

public enum Animal { Tiger=1, Lion=2 }
public enum Animal { Tiger='T', Lion='L' }

Although following syntax is also right

public enum Anumal { Tiger="TIG", Lion="LIO"}

How do I get the value in this case? If I convert it using ToString(), I get the KEY not the VALUE.

like image 659
Sham Avatar asked Jun 13 '13 11:06

Sham


People also ask

Can enums have string values?

The simplest way to convert enum values into string representation is by using a switch statement.

Is enum a key value pair?

An enum-like class that supports flags (up to 8192), has additional value-type data, description, and FastSerializer support.

How do I get the string value of an enum?

SOLUTION: int enumValue = 2; // The value for which you want to get string string enumName = Enum. GetName(typeof(EnumDisplayStatus), enumValue);

Can enums be strings Java?

Enum to String Conversion Example in Java There are two ways to convert an Enum to String in Java, first by using the name() method of Enum which is an implicit method and available to all Enum, and second by using toString() method.


5 Answers

If you really insist on using enum to do this, you can do it by having a Description attribute and getting them via Reflection.

    public enum Animal
    {
        [Description("TIG")]
        Tiger,
        [Description("LIO")]
        Lion
    }

    public static string GetEnumDescription(Enum value)
    {
        FieldInfo fi = value.GetType().GetField(value.ToString());

        DescriptionAttribute[] attributes =
            (DescriptionAttribute[])fi.GetCustomAttributes(
            typeof(DescriptionAttribute),
            false);

        if (attributes != null &&
            attributes.Length > 0)
            return attributes[0].Description;
        else
            return value.ToString();
    }

Then get the value by string description = GetEnumDescription(Animal.Tiger);

Or by using extension methods:

public static class EnumExtensions
{
    public static string GetEnumDescription(this Enum value)
    {
        FieldInfo fi = value.GetType().GetField(value.ToString());

        DescriptionAttribute[] attributes =
            (DescriptionAttribute[])fi.GetCustomAttributes(
            typeof(DescriptionAttribute),
            false);

        if (attributes != null &&
            attributes.Length > 0)
            return attributes[0].Description;
        else
            return value.ToString();
    }
}

Then use it by string description = Animal.Lion.GetEnumDescription();

like image 187
aiapatag Avatar answered Sep 29 '22 22:09

aiapatag


You can't use strings in enums. Use one or multiple dictionaries istead:

Dictionary<Animal, String> Deers = new Dictionary<Animal, String>
{
    { Animal.Tiger, "TIG" },
    { ... }
};

Now you can get the string by using:

Console.WriteLine(Deers[Animal.Tiger]);

If your deer numbers are in line ( No gaps and starting at zero: 0, 1, 2, 3, ....) you could also use a array:

String[] Deers = new String[] { "TIG", "LIO" };

And use it this way:

Console.WriteLine(Deers[(int)Animal.Tiger]);

Extension method

If you prefer not writing every time the code above every single time you could also use extension methods:

public static String AsString(this Animal value) => Deers.TryGetValue(value, out Animal result) ? result : null;

or if you use a simple array

public static String AsString(this Animal value)
{
    Int32 index = (Int32)value;
    return (index > -1 && index < Deers.Length) ? Deers[index] : null;
}

and use it this way:

Animal myAnimal = Animal.Tiger;
Console.WriteLine(myAnimal.AsString());

Other possibilities

Its also possible to do the hole stuff by using reflection, but this depends how your performance should be ( see aiapatag's answer ).

like image 41
Felix K. Avatar answered Sep 29 '22 22:09

Felix K.


That is not possible, the value of the enum must be mapped to a numeric data type. (char is actually a number wich is wirtten as a letter) However one solution could be to have aliases with same value such as:

public enum Anumal { Tiger=1, TIG = 1, Lion= 2, LIO=2}

Hope this helps!

like image 28
mortb Avatar answered Sep 29 '22 22:09

mortb


This isn't possible with Enums. http://msdn.microsoft.com/de-de/library/sbbt4032(v=vs.80).aspx You can only parse INT Values back.

I would recommend static members:

public class Animal 
{
    public static string Tiger="TIG";
    public static string Lion="LIO";
}

I think it's easier to handle.

like image 22
Smartis Avatar answered Sep 29 '22 21:09

Smartis


As DonBoitnott said in comment, that should produce compile error. I just tried and it does produce. Enum is int type actually, and since char type is subset of int you can assign 'T' to enum but you cannot assign string to enum.

If you want to print 'T' of some number instead of Tiger, you just need to cast enum to that type.

((char)Animal.Tiger).ToString()

or

((int)Animal.Tiger).ToString()
like image 22
Vajda Avatar answered Sep 29 '22 22:09

Vajda