Enumerate-Enum-C#

Enumerate Enum C# with Examples

How to enumerate Enum C#

Problem: We have enum declared in our class and we want to enumerate enum. How could we enumerate enum let’s together try to understand. Sometimes we get error message like “Enum is a type but used as a variable”. So how can we overcome from this issue!!!

Enum-prob-Enumeration
Enum is a type but used as a variable

 

Solution:

Let’s say we have a below enum in our code and we want to enumerate enum of DayOfWeek

    public enum DayOfWeek
    {
        Sunday = 0,
        Monday = 1,
        Tuesday = 2,
        Wednesday = 3,
        Thursday = 4,
        Friday = 5,
        Saturday = 6
    }

There are two ways to enumerate enum:

  1. var values = Enum.GetValues(typeof(myenum))
  2. var values = Enum.GetNames(typeof(myenum))

The first will give you values in form on a array of object, and the second will give you values in form of array of String.

Find below code snippet for solution of “How to enumerate Enum in C#?”

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Enumerate_Enum_csharp
{
    class Program
    {
        public enum DayOfWeek
        {
            Sunday = 0,
            Monday = 1,
            Tuesday = 2,
            Wednesday = 3,
            Thursday = 4,
            Friday = 5,
            Saturday = 6
        }

        static void Main(string[] args)
        {
            //Code snippet-1
            foreach (DayOfWeek ObjDayOfWeek in Enum.GetValues(typeof(DayOfWeek)))
            {
                DoSomething(ObjDayOfWeek);
            }

            //Code snippet-2
            //I think caching the array would speed it up considerably. 
            //It looks like you're getting a new array (through reflection) every time.
            //Optimization of first code snippet
            Array enums = Enum.GetValues(typeof(DayOfWeek));
            foreach (DayOfWeek ObjDayOfWeek in enums)
            {
                DoSomething(ObjDayOfWeek);
            }

            //Code snippet-3
            string[] enumsString = Enum.GetNames(typeof(DayOfWeek));
            foreach (string strDayOfWeek in enumsString)
            {
                Console.WriteLine(strDayOfWeek);
            }
        }

        private static void DoSomething(DayOfWeek ObjDayOfWeek)
        {
            Console.WriteLine(ObjDayOfWeek.ToString() + " ID=" + (int)ObjDayOfWeek);
        }
    }
}

We could also use alternate way of implementation as below:

typeof(DayOfWeek).GetEnumValues;
typeof(DayOfWeek).GetEnumName(object Value);

Output:

Enumerate-Enum-Output

 

Folks, this is how we could enumerate Enum in C#. As I have explained two different ways to enumerate Enum, if anyone is having another way to enumerate Enum in C#, kindly share with us.

Leave a Reply