Assigning a string value to an enums and then finding the enum by value

I solved the problem by using the Description attribute on the enum. the solution is as follows. I use the extension method to get the description. the code to get the description is taken from this link http://blog.spontaneouspublicity.com/post/2008/01/17/Associating-Strings-with-enums-in-C.aspx. thanks for your replies.

    public enum Fruit
{
    [Description("Apple")]
    A,
    [Description("Banana")]
    B,
    [Description("Cherry")]
    C
}

public static class Util
{
    public static T StringToEnum<T>(string name)
    {
        return (T)Enum.Parse(typeof(T), name);
    }

    public static string ToDescriptionString(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();
    }
}

You can put the values in a Dictionary to efficiently look them up:

Dictionary<string, Fruit> fruitValues = new Dictionary<string, Fruit>();
fruitValues.Add("A", Fruit.Apple);
fruitValues.Add("B", Fruit.Banana);
fruitValues.Add("C", Fruit.Cherry);

Lookup:

string dataName = "A";
Fruit f = fruitValues[dataName];

If the value may be non-existent:

string dataName = "A";
Fruit f;
if (fruitValues.TryGetValue(dataName, out f)) {
  // got the value
} else {
  // there is no value for that string
}

I have written a library that handles precisely this problem. It was originally intended just to do the opposite (return a string value from and Enum) but once I'd written that, being able to parse a string back into its Enum, was only a short step.

The library is called EnumStringValues and is available from nuget in VS (package page is here too: https://www.nuget.org/packages/EnumStringValues) SourceCode is on GitHub here: https://github.com/Brondahl/EnumStringValues

Thoughts and comments are welcome. Inspiration obviously comes from the well publicised Attribute approach referenced in other answers here.

Tags:

C#

Enums