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.
2 Answers 2
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.
2 Comments
<TEnumType> wouldn't help us, because we aren't returning TEnumType[], but rather an int[], byte[], etc - which we can't tell via the generics.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.
SomeEnum, or asbyteetc?