---
title: "How to enumerate an enum?"  
description: "How to enumerate an enum?"  
author: "Steilla Mitchel"  
published: 2023-07-12  
updated: 2023-07-13  
canonical: https://www.mindstick.com/forum/159043/how-to-enumerate-an-enum  
category: "c#"  
tags: ["c#", "class"]  
reading_time: 2 minutes  

---

# How to enumerate an enum?

How to enumerate an [enum](https://www.mindstick.com/forum/159626/how-can-i-cast-a-string-to-an-enum)?

## Replies

### Reply by Aryan Kumar

There are two ways to enumerate an enum in C#:

- **Using a foreach loop:**

C#

```plaintext
using System;

public enum Colors
{
    Red,
    Green,
    Blue
}

public class EnumerateEnum
{
    public static void Main(string[] args)
    {
        // Enumerate the enum using a foreach loop.
        foreach (Colors color in Colors)
        {
            Console.WriteLine("The color is {0}.", color);
        }
    }
}
```

This code first creates an enum called `Colors`. The `Colors` enum has three values: `Red`, `Green`, and `Blue`.

The code then uses a foreach loop to enumerate the `Colors` enum. The foreach loop will iterate through each value of the `Colors` enum and print the value to the console.

- **Using the** `Enum.GetValues()` **method:**

C#

```plaintext
using System;

public enum Colors
{
    Red,
    Green,
    Blue
}

public class EnumerateEnum
{
    public static void Main(string[] args)
    {
        // Enumerate the enum using the Enum.GetValues() method.
        object[] colors = Enum.GetValues(typeof(Colors));

        // Iterate through the colors array and print each value to the console.
        for (int i = 0; i < colors.Length; i++)
        {
            Colors color = (Colors)colors[i];
            Console.WriteLine("The color is {0}.", color);
        }
    }
}
```

This code first creates an enum called `Colors`. The `Colors` enum has three values: `Red`, `Green`, and `Blue`.

The code then uses the `Enum.GetValues()` method to get an array of all the values of the `Colors` enum. The `Enum.GetValues()` method takes the type of the enum as a parameter.

The code then iterates through the array of values and prints each value to the console.


---

Original Source: https://www.mindstick.com/forum/159043/how-to-enumerate-an-enum

Copyright © MindStick Software Pvt. Ltd. This Markdown version is provided for developers, AI systems, and offline reading.
