---
title: "How to loop through an enum in C#?"  
description: "How to loop through an enum in C#?"  
author: "Steilla Mitchel"  
published: 2024-06-09  
updated: 2024-06-10  
canonical: https://www.mindstick.com/forum/160699/how-to-loop-through-an-enum-in-c-sharp  
category: "c#"  
tags: ["c#", ".net"]  
reading_time: 2 minutes  

---

# How to loop through an enum in C#?

How to loop through an [enum in C#](https://www.mindstick.com/forum/33625/how-to-use-enum-in-c-sharp-dot-net)?

## Replies

### Reply by Ravi Vishwakarma

Looping through an [enum](https://www.mindstick.com/forum/159626/how-can-i-cast-a-string-to-an-enum) in C# can be done using the `Enum.GetValues` method, which returns an array of the values of the constants in a specified enumeration. This allows you to use a `foreach` loop to iterate over the enum values.

Here’s how you can loop through an enum:

## Example Enum Definition

```cs
public enum DaysOfWeek
{
   Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday
}
```

## Looping Through the Enum

You can loop through the `DaysOfWeek` enum as follows:

```cs
foreach (DaysOfWeek day in Enum.GetValues(typeof(DaysOfWeek)))
{
   Console.WriteLine(day);
}
```

## This will output:

```plaintext
Sunday
Monday
Tuesday
Wednesday
Thursday
Friday
Saturday
```

## Complete Example

Here is a complete example with the enum definition and the loop:

```cs
using System;
public class Program
{
    public enum DaysOfWeek
    {
        Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday
    }
    public static void Main()
    {
        foreach (DaysOfWeek day in Enum.GetValues(typeof(DaysOfWeek)))
        {
            Console.WriteLine(day);
        }
    }
}
```

### Additional Considerations

**Enum Names:** If you need to get the names of the enum values as strings, you can use the `Enum.GetNames` method:

```cs
foreach (string name in Enum.GetNames(typeof(DaysOfWeek)))
{
    Console.WriteLine(name);
}
```

**Enum Parsing:** You can parse a string to get the corresponding enum value using `Enum.Parse`

```cs
string dayName = "Monday";
DaysOfWeek day = (DaysOfWeek)Enum.Parse(typeof(DaysOfWeek), dayName);
Console.WriteLine(day);  // Output: Monday
```

**Checking if Value is Defined:** You can check if a value is defined in the enum using `Enum.IsDefined`

```cs
bool isDefined = Enum.IsDefined(typeof(DaysOfWeek), "Monday");
Console.WriteLine(isDefined);  // Output: True
```

Looping through an enum is a straightforward task in C# and can be done efficiently with the built-in `Enum.GetValues` and `Enum.GetNames` methods. This approach ensures that your code is both clean and easy to maintain.


---

Original Source: https://www.mindstick.com/forum/160699/how-to-loop-through-an-enum-in-c-sharp

Copyright © MindStick Software Pvt. Ltd. This Markdown version is provided for developers, AI systems, and offline reading.
