3

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.

Community
  • 1
  • 1
gdoron
  • 147,333
  • 58
  • 291
  • 367

2 Answers2

5

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.

Marc Gravell
  • 1,026,079
  • 266
  • 2,566
  • 2,900
  • You can set the method to get the Enum type as a generic param, but it won't change a thing, right? – gdoron Oct 31 '11 at 09:33
  • @gdoron indeed, have it `` wouldn't help us, because we aren't returning `TEnumType[]`, but rather an `int[]`, `byte[]`, etc - which we can't tell via the generics. – Marc Gravell Oct 31 '11 at 09:34
2

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.

Michael B
  • 7,512
  • 3
  • 31
  • 57
  • Wow thanks! But still you can't return the strongly type list a function, right? – gdoron Nov 11 '11 at 06:48
  • That's correct Enums are not generic types in the traditional way, if enums were generic like say `MyEnum: Enum` then this would be possible. – Michael B Nov 11 '11 at 15:44