How to enumerate enums when the type of enumeration is known only at runtime?

I found this answer on stackoverflow for listing an enum of a specific type:

var values = (SomeType[])Enum.GetValues(typeof(SomeType));

      

This works great if I hardcode the enum type. But I need to set the type at runtime. I've tried the following but it doesn't work:

var values = (typeof(T)[])Enum.GetValues(typeof(T));

      

+3


source to share


4 answers


Yours T

already has a type Type

. No need to use another typeof

. A simple cast to T[]

should suffice:



T[] values = (T[]) Enum.GetValues(typeof(T));

      

0


source


typeof(T)

usually returns an object to you Type

, so the compiler thinks you want to apply indexing to that object.

Try using:



Enum.GetValues(typeof(T)).Cast<T>()

+1


source


public static IEnumerable<T> GetValues<T>()
{
    return Enum.GetValues(typeof(T)).Cast<T>();
}

      

See fiddle

+1


source


You can use a method Cast<T>()

to end the process and a method typeof(T).IsEnum

to check the type ( T

must be an enumerated type).

Target method:

public static IEnumerable<T> GetValues<T>()
{
  if (!typeof(T).IsEnum) 
    throw new ArgumentException("T must be an enumerated type");
  return Enum.GetValues(typeof(T)).Cast<T>();
}

      

Usage example:

public enum EnumFoo
{
  Foo1, Foo2
}
public enum EnumBar
{
  Bar1, Bar2
}
public void Main()
{
  foreach (var value in GetValues<EnumFoo>())
    Console.WriteLine(value); // Foo1 Foo2
  foreach (var value in GetValues<EnumBar>())
    Console.WriteLine(value); // Bar1 Bar2
}

      

+1


source







All Articles