#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");
            }
Advertisements