views:

84

answers:

2

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.

+10  A: 

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.

Reed Copsey
Wow, talk about similar examples. +1.
Ryan Brunner
@Ryan: Yeah - not too different ;)
Reed Copsey
Great answer, but I'm curious: why `++i`?
Ben McCormack
@Ben: Instead of i++? It's a habit from my C/C++ days where it mattered... (and where I still write a fair amount of code, so I like to keep the habit)
Reed Copsey
@Reed ahh, thanks for the explanation. Yes, I was curious in reference to `i++`. While I knew it was allowed in C#, I had never seen anyone use it and wasn't sure if there was a difference.
Ben McCormack
@Ben: See http://www.devx.com/tips/Tip/12634 When you use postfix operators, you typically force a constructor call. In some compilers, they're actually even slower on primitives (most modern ones optimize it out, though).
Reed Copsey
@Ben: I don't like to micro-optimize, but I also try to just build habits that prevent having to optimize later :) This is one I've picked up over the years.
Reed Copsey
+1  A: 

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);
        }
    }
epitka