How to Loop through or Iterate over all Enum Values in C# ?

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

  1. Safi
    April 3, 2014
    Reply

    Thanks for your post, it helped me 🙂

Leave A Reply

Your email address will not be published. Required fields are marked *

You May Also Like

This C# program calculates and displays an upper triangular matrix based on user input. Problem Statement: The program takes the...
This C# program serves as a demonstration of bitwise operators, which are fundamental operators used for manipulating individual bits in...
This C# program is designed to interchange or swap the columns of a matrix. A matrix is a two-dimensional array...