Monstieur
Monstieur

Reputation: 8102

Get underlying value of a generic Enum

I want to generate the list of underlying values and names for a given generic Enum type. I want the native underlying values (as objects).

    public static ReadOnlyCollection<EnumerationMember> ListFromEnum<TEnum>()
    {
        Type enumType = typeof(TEnum);
        if (!enumType.IsEnum)
        {
            throw new InvalidOperationException("TEnum is not an enum");
        }

        Type underlyingType = Enum.GetUnderlyingType(enumType);
        TEnum[] enumValues = (TEnum[])Enum.GetValues(enumType);

        return enumValues
            .Select(ev => new EnumerationMember(
                (???)ev,
                EnumerationExtension.GetDescription(enumType, ev)))
            .ToList()
            .AsReadOnly();
    }

    public class EnumerationMember
    {
        public EnumerationMember(object value, string description)
        {
            this.Value = value;
            this.Description = description;
        }

        public object Value { get; private set; }

        public string Description { get; private set; }
    }

Upvotes: 2

Views: 1029

Answers (2)

Jamiec
Jamiec

Reputation: 136104

Here is some working code for you, it uses Convert.ChangeType

public static ReadOnlyCollection<EnumerationMember> ListValuesFromEnum<T>()
{
    Type enumType = typeof(T);
    Type underlyingType = Enum.GetUnderlyingType(enumType);
    T[] enumValues = (T[])Enum.GetValues(enumType);

    return enumValues
        .Select(ev => new EnumerationMember(Convert.ChangeType(ev,underlyingType), ev.ToString()))
        .ToList()
        .AsReadOnly();
}        

And here's a live demo: http://rextester.com/EHOE12097

Upvotes: 0

Marc Gravell
Marc Gravell

Reputation: 1062780

At the simplest:

.Select(ev => Convert.ChangeType(ev, underlyingType))

But my preference would be to return a right-typed array - you don't even need the convert step then:

public static Array ListValuesFromEnum<T>()
{
    Type enumType = typeof(T);
    Type underlyingType = Enum.GetUnderlyingType(enumType);
    Array enumValues = Enum.GetValues(enumType);

    var arr = Array.CreateInstance(underlyingType, enumValues.Length);
    enumValues.CopyTo(arr, 0);
    return arr;
}

Upvotes: 6

Related Questions