Sometimes , it may be necessary for the C# developers to loop through or iterate over all the Enum Values in solving a particular task. In this blog post , i will explain with an example on How to Loop through or Iterate over all Enum Values in C# ?
How to Loop through or Iterate over all Enum Values in C# ?
We use the keyword enum to create enumeration in c#. For example , and enum of movies can be created by
enum Movies { Thuppaki, Maatran, Ghilli, Nanban };
In the above example , Thuppaki will be assigned 0 , Maatran will be assigned 1 , Ghilli will be assigned 2 and Nanban will be assigned 3.
The methods Enum.Getnames and Enum.GetValues are used in c# to retreive the enum names and its values .
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using System.Windows.Forms; namespace WindowsFormsApplication1 { static class Program { static void Main() { Traverse(); } enum Movies { Thuppaki, Maatran, Ghilli, Nanban}; static void Traverse() { foreach(var i in Enum.GetNames(typeof(Movies))) { MessageBox.Show(i); } foreach (var i in Enum.GetValues(typeof(Movies))) { MessageBox.Show(((int)i).ToString()); } } } }
1 Comment
Thanks for your post, it helped me 🙂