Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to iterate through all enum values? [duplicate]

Tags:

c#

enumeration

Possible Duplicate:
C#: How to enumerate an enum?

The subject says all. I want to use that to add the values of an enum in a combobox.

Thanks

vIceBerg

like image 560
vIceBerg Avatar asked Sep 30 '08 18:09

vIceBerg


People also ask

Can enum have duplicate values?

Two enum names can have same value. For example, in the following C program both 'Failed' and 'Freezed' have same value 0.

Can we loop through enum?

Enums don't have methods for iteration, like forEach() or iterator(). Instead, we can use the array of the Enum values returned by the values() method.

Can you loop through all enum values in C#?

Yes. Use GetValues() method in System. Enum class.


2 Answers

string[] names = Enum.GetNames (typeof(MyEnum)); 

Then just populate the dropdown withe the array

like image 55
albertein Avatar answered Sep 18 '22 13:09

albertein


I know others have already answered with a correct answer, however, if you're wanting to use the enumerations in a combo box, you may want to go the extra yard and associate strings to the enum so that you can provide more detail in the displayed string (such as spaces between words or display strings using casing that doesn't match your coding standards)

This blog entry may be useful - Associating Strings with enums in c#

public enum States {     California,     [Description("New Mexico")]     NewMexico,     [Description("New York")]     NewYork,     [Description("South Carolina")]     SouthCarolina,     Tennessee,     Washington } 

As a bonus, he also supplied a utility method for enumerating the enumeration that I've now updated with Jon Skeet's comments

public static IEnumerable<T> EnumToList<T>()     where T : struct {     Type enumType = typeof(T);      // Can't use generic type constraints on value types,     // so have to do check like this     if (enumType.BaseType != typeof(Enum))         throw new ArgumentException("T must be of type System.Enum");      Array enumValArray = Enum.GetValues(enumType);     List<T> enumValList = new List<T>();      foreach (T val in enumValArray)     {         enumValList.Add(val.ToString());     }      return enumValList; } 

Jon also pointed out that in C# 3.0 it can be simplified to something like this (which is now getting so light-weight that I'd imagine you could just do it in-line):

public static IEnumerable<T> EnumToList<T>()     where T : struct {     return Enum.GetValues(typeof(T)).Cast<T>(); }  // Using above method statesComboBox.Items = EnumToList<States>();  // Inline statesComboBox.Items = Enum.GetValues(typeof(States)).Cast<States>(); 
like image 34
Ray Hayes Avatar answered Sep 21 '22 13:09

Ray Hayes