gray laptop computer showing html codes in shallow focus photography

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

C# Compiler Error CS0442 – ‘Property’: abstract properties cannot have private accessors Reason for the Error You’ll get this error...
This is a really simple one . Below is a simple example of an enum called “Designation” defined with the...
This blog post explain the usage of the Checked Block in .NET and how you can use them in Visual...