Is there a way to iterate and reflect member names and values ​​contained in enums?

Let's say I have the following enum :

 public enum Colors { White = 10, Black = 20, Red = 30, Blue = 40 } 

I am wondering if there is a way to iterate through all the Colors members to find the names of the participants and their values.

+7
reflection enums c # iteration enumeration
source share
2 answers

You can use Enum.GetNames and Enum.GetValues :

 var names = Enum.GetNames(typeof(Colors)); var values = Enum.GetValues(typeof(Colors)); for (int i=0;i<names.Length;++i) { Console.WriteLine("{0} : {1}", names[i], (int)values.GetValue(i)); } 

Note. When I tried to run the code using values[i] , it threw an exception because values is of type Array .

+12
source share

You can do something like this

  for (int i = 0; i < typeof(DepartmentEnum).GetFields().Length - 1; i++) { DepartmentEnum de = EnumExtensions.NumberToEnum<DepartmentEnum>(i); pairs.Add(new KeyValuePair<string, string>(de.ToDescription(), de.ToString())); } 

Here is the extension itself:

  public static class EnumExtensions { public static string ToDescription(this Enum en) { Type type = en.GetType(); MemberInfo[] memInfo = type.GetMember(en.ToString()); if (memInfo != null && memInfo.Length > 0) { object[] attrs = memInfo[0].GetCustomAttributes(typeof(DescriptionAttribute),false); if (attrs != null && attrs.Length > 0) return ((DescriptionAttribute)attrs[0]).Description; } return en.ToString(); } public static TEnum NumberToEnum<TEnum>(int number ) { return (TEnum)Enum.ToObject(typeof(TEnum), number); } } 
+1
source share

All Articles