0

I have an EnumHelper class to do some value to enum and reverse type conversions. I have one to convert a string to an enum value and one to get the description of an enum value and having trouble putting these two together such that you supply a string and enum type and have it return the enum value's description. i.e.

Given the enum below, provide a static method with the string "ScanItemBarcode" (which is stored in the database) and return "Scan Item Barcode" (the enum value's description).

public enum ItemValidationTypes
{
    [Description("Scan Item Barcode")]
    ScanItemBarcode,

    [Description("Scan Location/Container")]
    ScanLocationContainer,
}

My code to convert string to enum value:

public static T GetEnumFromString<T>(string enumStringValue)
    where T : struct, IConvertible
{
    Type enumType = typeof(T);
    if (!enumType.IsEnum)
    {
        throw new Exception("T must be an Enum type.");
    }

    T val;
    return Enum.TryParse<T>(enumStringValue,true,out val) ? val : default(T);
}

Then my code to get enum description from enum value:

public static string GetEnumDescription(Enum enumElement)
{
    FieldInfo fi = enumElement.GetType().GetField(enumElement.ToString());

    DescriptionAttribute[] attributes =
        (DescriptionAttribute[])fi.GetCustomAttributes(
        typeof(DescriptionAttribute),
        false);

    if (attributes != null &&
        attributes.Length > 0)
        return attributes[0].Description;
    else
        return enumElement.ToString();
}

Finally, the problem code, my attempt to combine the two above:

public static string GetEnumDescription<T>(string strEnumValue)
    where T : struct, IConvertible
{
    T enumElement = GetEnumFromString<T>(strEnumValue);
    return GetEnumDescription((Enum)enumElement);
}

The Error produced from the attempt to combine is that you can't convert type T to System.Enum.

crichavin
  • 4,672
  • 10
  • 50
  • 95

0 Answers0