How to loop through an enum in C#
3 Answers
Know the answer? Post it. Somebody with the same question will find it here.
Know the answer? Post it. Somebody with the same question will find it here.
Answer a question in the forums and earn +20 SHARP for every answer.
See unanswered questions
DevSocialUpcoming · 3rd editionAI Agents ConferenceDec 1–3, 2026Live onlineFree to attend5days leftRegister
Rajanikant HawaldarRank #110 · 20.2K reputationPosted Jul 12, 2022, 5:10 AM EDT
In C# an enum is used to assign constant names to a group of numeric integer values. It makes constant values more readable, for example, WeekDays.Monday is more readable than number 0 when referring to the day in a week.An enum can be looped through using Enum.GetNames(), Enum.GetNames(), Enum.GetValues(), or Enum.GetValues() static methods with the foreach loop.The following example gets the names of an enum using the Enum.GetNames() method.
Mahesh ChandRank #1 · 393.3K reputationPosted Jul 12, 2022, 9:15 AM EDT
Vishal YelveRank #178 · 13.6K reputationPosted Jul 12, 2022, 7:31 AM EDT
var values = Enum.GetValues(typeof(Foos));ORvar values = Enum.GetValues(typeof(Foos)).Cast(); Generic helper functionpublic static class EnumUtil { public static IEnumerable GetValues() { return Enum.GetValues(typeof(T)).Cast(); } } usagevar values = EnumUtil.GetValues();