gdoron
gdoron

Reputation: 150253

C#: Generic list of enum values

Is there a way to create a method that gets an enum type as a parameter, and returns a generic list of the enum underlying type from it's values, no matter if the underlying type is int\short byte etc'...
I saw this answer of Jon Skeet, but it looks way too complicated.

Upvotes: 4

Views: 8348

Answers (2)

Michael B
Michael B

Reputation: 7567

While Marc's answer isn't wrong its somewhat unnecessary. Enum.GetValues(type) returns a TEnum[] so this method is kind of unnecessary as if you know the underlying type you can just cast TEnum[] to its underlying type array.

var underlyingArray = (int[])Enum.GetValues(typeof(StringComparison));

is valid C# that will compile and won't throw an exception at runtime. Since you wanted a list once you have the array you can pass it to the List<Tunderlying> constructor or you can just call the ToArray() extension method.

Edit: you could write the function as such::

public static TUnderlying[] GetValuesAs<TUnderlying>(type enumType)
{
     return Enum.GetValues(enumType) as TUnderlying[];
}

But then you would have to know the underlying type first.

Upvotes: 2

Marc Gravell
Marc Gravell

Reputation: 1062550

If you want to pass in a Type, it can't really be usefully generic - you'd have to return a single type that isn't directly related to the input, hence something like:

    public static Array GetUnderlyingEnumValues(Type type)
    {
        Array values = Enum.GetValues(type);
        Type underlyingType = Enum.GetUnderlyingType(type);
        Array arr = Array.CreateInstance(underlyingType, values.Length);
        for (int i = 0; i < values.Length; i++)
        {
            arr.SetValue(values.GetValue(i), i);
        }
        return arr;
    }

This is a strongly-typed vector underneath, so you could cast that to int[] etc.

Upvotes: 5

Related Questions