get enum from string code example

Example 1: java get enum from string

public enum Hello {
  A, B, C
};

val = Hello.valueOf("A") // Case sensitive and cannot have spaces in the string
val.equals(Hello.A) // returns true

Example 2: get enum from enum description

public static int GetEnumFromDescription(string description, Type enumType)
{
    foreach (var field in enumType.GetFields())
    {
        DescriptionAttribute attribute
            = Attribute.GetCustomAttribute(field, typeof(DescriptionAttribute))as DescriptionAttribute;
        if(attribute == null)
            continue;
        if(attribute.Description == description)
        {
            return (int) field.GetValue(null);
        }
    }
    return 0;
}

Tags:

Misc Example