Sham Sham - 6 months ago 34
C# Question

Creating enums having Key Value as string

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"}


but how will i get value in this case, as if i convert it in tostring, i will get KAY not VALUE.

Answer Source

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) => Deers[(Int32)value];

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 ).