Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert String to Enum based on enum name

Tags:

c#

.net

enums

So we have our enums setup like this:

[CorrelatedNumeric(0)]
[Description("USD")]
[SequenceNumber(10)]
USD = 247

Basically, another function can provide the string "USD" to me, but not the exact enum because the source of it is Excel and we can't make our users remember the enum values ;) nor would that make much sense.

Is there a way in c# to get from "USD" to 247 from having our enums setup as they are above?

like image 741
slandau Avatar asked Nov 29 '22 16:11

slandau


2 Answers

Would Enum.TryParse() or Enum.Parse() do what you need?

Currency cValue = (Currency) Enum.Parse(typeof(Currency), currencyString); 
like image 180
Leon Avatar answered Dec 18 '22 01:12

Leon


Absolutely - build a Dictionary<string, YourEnumType> by reflection. Just iterate over all the fields in the enum and find the attribute values, and build up the dictionary that way.

You can see how I've done something similar in Unconstrained Melody for the description attribute, in EnumInternals:

// In the static initializer...
ValueToDescriptionMap = new Dictionary<T, string>();
DescriptionToValueMap = new Dictionary<string, T>();
foreach (T value in Values)
{
    string description = GetDescription(value);
    ValueToDescriptionMap[value] = description;
    if (description != null && !DescriptionToValueMap.ContainsKey(description))
    {
        DescriptionToValueMap[description] = value;
    }
}

private static string GetDescription(T value)
{
    FieldInfo field = typeof(T).GetField(value.ToString());
    return field.GetCustomAttributes(typeof(DescriptionAttribute), false)
                .Cast<DescriptionAttribute>()
                .Select(x => x.Description)
                .FirstOrDefault();
}

Just do the same thing for your own attribute type.

like image 26
Jon Skeet Avatar answered Dec 18 '22 01:12

Jon Skeet