tags:

views:

119

answers:

6

I have an enum that I'd like to display all possible values of. Is there a way to get an array or list of all the possible values of the enum instead of manually creating such a list? e.g. If I have an enum:

public enum Enumnum { TypeA, TypeB, TypeC, TypeD }

how would I be able to get a List<Enumnum> that contains { TypeA, TypeB, TypeC, TypeD }?

A: 

You can use

Enum.GetValues(typeof(SomeEnum)).Cast<SomeEnum>().ToArray();

This returns an array!

Mitchel Sellers
A: 

You can use Enum.GetValues.

Oded
+8  A: 

This gets you a plain array of the enum values using Enum.GetValues:

var valuesAsArray = Enum.GetValues(typeof(Enumnum));

And this gets you a generic list:

var valuesAsList = Enum.GetValues(typeof(Enumnum)).Cast<Enumnum>().ToList();
0xA3
Thanks, exactly what I was looking for!
Mark LeMoine
This makes me always wonder why `Enumnum.GetValues()` and `Enumnum.GetNames()` doesn't exist.
dalle
+2  A: 
Enum.GetValues(typeof(Enumnum));

returns an array of the values in the Enum.

Duracell
A: 

Try this code:

Enum.GetNames(typeof(Enumnum));

This return a string[] with all the enum names of the chosen enum.

Øyvind Bråthen
Returns *names* of the enum values; OP seems to be after the *values* themselves.
Michael Petrotta
A: 

with this:

string[] myArray = Enum.GetNames(typeof(Enumnum));

and you can access values array like so:

Array myArray = Enum.GetValues(typeof(Enumnum));
Dr TJ
Enum.GetValues doesn't return a string[]
messenger