Sham
Sham

Reputation: 691

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

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

Upvotes: 7

Views: 30576

Answers (6)

CodeNinja.it
CodeNinja.it

Reputation: 1

Possible alternative solution:

public enum SexCode : byte { Male = 77, Female = 70 } // ascii values

after that, you can apply this trategy in your class

class contact {
    public SexCode sex {get; set;} // selected from enum
    public string sexST { get {((char)sex).ToString();}} // used in code
}

Upvotes: 0

Felix K.
Felix K.

Reputation: 6281

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

Upvotes: 8

aiapatag
aiapatag

Reputation: 3430

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();

Upvotes: 10

Vajda
Vajda

Reputation: 1794

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

Upvotes: 1

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.

Upvotes: 2

mortb
mortb

Reputation: 9859

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!

Upvotes: 2

Related Questions