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;
}
1
  • 2
    Enums are just ints with sugar on top, so they are indeed structs. Commented Jul 30, 2012 at 10:06

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

2 Comments

and also enums are actually structs
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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.