Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to iterate and reflect the member names and values contained in enumerations?

Let's say I have the following enum:

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

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

like image 281
Ben McCormack Avatar asked Feb 05 '10 19:02

Ben McCormack


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.

like image 54
Reed Copsey Avatar answered Nov 16 '22 21:11

Reed Copsey


You could 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);
        }
    }
like image 40
epitka Avatar answered Nov 16 '22 19:11

epitka