#465 – Dumping All Names and Values for an Enumerated Type

You can use the Enum.GetValues method to iterate through all values of an enumerated type.  You can use this method to dump out the name and value of each enumeration value in the enumerated type.

        public enum Moods
            NOMOOD = 0,
            Ambivalent = 1,
            Crabby = 10,
            Grouchy = Crabby - 1,
            Happy = 42,
            SuperHappy = 2 * Happy
foreach (Moods mood in Enum.GetValues(typeof(Moods)))
    Console.WriteLine("{0} - {1}", mood, (int)mood);

#367 – Iterating through All Possible Values of an Enumeration Type

There are occasions when it’s desirable to iterate through all possible values of an enumeration type.  You can do this using the static Enum.GetValues method.

Suppose that we have an enumeration type representing the days of the week.

    public enum Days { Sun, Mon, Tues, Wed, Thurs, Fri, Sat };

We might want to iterate through all possible values of the Days enumeration, for example to initialize some data structure.

            private Dictionary<Days, LogMessage> dailyMessages = new Dictionary<Days, LogMessage>();

            foreach (Days day in Enum.GetValues(typeof(Days)))
                dailyMessages[day] = new LogMessage("Default message");