3

Possible Duplicate:
C# Iterating through an enum? (Indexing a System.Array)

All I want to do is write a function that can take any enum as a parameter and print the values of that enum but it doesn't seem possible:

For example, I'd like to do this:

void PrintEnumValues(Enum e) { ... }

enum Example1 { a, b }
enum Example2 { one, two }

PrintEnumValues(Example1);
PrintEnumValues(Example2);

Is something like this possible?

Community
  • 1
  • 1
Sachin Kainth
  • 45,256
  • 81
  • 201
  • 304
  • 1
    Try actually writing it, and see if you can prove yourself wrong. – BoltClock Dec 07 '11 at 10:08
  • Do you mean you want your output to be "a b" or "a" or "0" or "0 1"? I.E. do you mean to print out the whole set or only one instance? When you say values do mean the string representation or the int? – Buh Buh Dec 07 '11 at 10:14

6 Answers6

9
class Program
{
    enum Example1 { a, b }
    enum Example2 { one, two }

    static void Main()
    {
        PrintEnumValues(default(Example1));
        PrintEnumValues(default(Example2));
    }

    static void PrintEnumValues(Enum e) 
    {
        foreach (var item in Enum.GetValues(e.GetType()))
        {
            Console.WriteLine(item);         
        }
    }
}
Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928
2

possible but you need to make reflection body of PrintEnumValues.

...
PrintEnumValues(typeof(Example1));
...


void PrintEnumValues(Type type)
{
 //sample: Enum.GetNames(type)
 //sample: Enum.GetValues(type)
}
Nuri YILMAZ
  • 4,291
  • 5
  • 37
  • 43
1

You can use Enum.GetValues() and pass the type of the enum to get an array of the values.

ChristiaanV
  • 5,401
  • 3
  • 32
  • 42
0

Here is my suggestion for you:

void PrintEnumValues<TEnum>() 
{
    if (!typeof(Enum).IsAssignableFrom(typeof(TEnum)))
    {
        return;
    }
    foreach (var name in Enum.GetNames(typeof(TEnum)))
    {
        // Print name
    }
}

Call that function like that:

PrintEnumValues<Example1>(); 
PrintEnumValues<Example2>(); 
Fischermaen
  • 12,238
  • 2
  • 39
  • 56
0
    enum Example1 
    { a, b }
    enum Example2 
    { one, two }

    public T[] GetEnumMembers<T>() where T : struct
    {
        T[] values = (T[])Enum.GetValues(typeof(T));
        return values;
    }

Then use this as:

    var values = GetEnumMembers<Example1>();
Azhar Khorasany
  • 2,712
  • 16
  • 20
0

You said in your comment I'm not asking about iterating. So I assume you want to print "a":

PrintEnumValues(Example1.a);

NOT

PrintEnumValues(Example1);
Buh Buh
  • 7,443
  • 1
  • 34
  • 61