3

I would like to have a method that will parse from a nullable database column an enum. I wrote this method below (and had to restrict T to a struct to make it compile).

It does compile, but I believe its wrong as Enums are not structs? If so, how do I restrict the generic method to say I am expecting a ValueType you don't have to complain at me that "Only non-nullable value type could be underlying of 'System.Nullable'

private static T? ParseEnum<T>(DataRow row, string columnName)
    where T : struct
{
    T? value = null;
    try
    {
        if (row[columnName] != DBNull.Value)
        {
            value = (T)Enum.Parse(
                typeof(T),
                row[columnName].ToString(),
                true);
        }
    }

    catch (ArgumentException) { }

    return value;
}
M Afifi
  • 4,645
  • 2
  • 28
  • 48

2 Answers2

5

Unfortunately there's no constraint available in C# that allows you to restrict that a given type is an enum. In IL there's such notion though. Jon blogged about it.

Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928
2

I think you could try to use dynamic and create generic list of enum at runtime

    public static dynamic ToValues(this Type enumType)
    {
        var values = Enum.GetValues(enumType);
        Type list = typeof(List<>);
        Type resultType = list.MakeGenericType(enumType);
        dynamic result =  Activator.CreateInstance(resultType);
        foreach (var value in values)
        {
            dynamic concreteValue = Enum.Parse(enumType, value.ToString());
            result.Add(concreteValue);
        }
        return result;
    }

As a result you'll have List of concrete enum

GSerjo
  • 4,725
  • 1
  • 36
  • 55