Question

How to Loop Through Enum Values in C#

csharp.netenumslanguage-features

Question

Given this C# enum:

public enum Foos
{
    A,
    B,
    C
}

How can you loop through all possible values of Foos?

For example, is there a way to do something like this?

foreach (var foo in Foos)
{
    // use foo
}

The goal is to iterate through every enum member in C#.

Short Answer

By the end of this page, you will understand how to iterate through every value in a C# enum, why enums cannot be looped over directly, and how Enum.GetValues() is commonly used to solve this. You will also see practical examples, common mistakes, and how this pattern appears in real codebases.

Concept

In C#, an enum is a special type that represents a fixed set of named constants. It is useful when a variable should only be one of a known set of values, such as days of the week, order statuses, or user roles.

An enum defines a type, not a collection you can directly loop over. That is why this does not work:

foreach (var foo in Foos)
{
}

Foos is a type name, not an enumerable object.

To iterate through enum values, you need to ask .NET to give you the values as a collection. The standard way is:

Enum.GetValues(typeof(Foos))

This returns all defined values of the enum so you can use them in a foreach loop.

This matters in real programming because enums are often used to:

  • build dropdown lists
  • validate allowed states
  • generate menus or options
  • apply logic for every possible status
  • test all enum cases

When you know how to enumerate an enum, you can write cleaner and more maintainable code instead of hardcoding each value manually.

Mental Model

Think of an enum like a printed list of allowed labels on a card:

  • A
  • B
  • C

The enum itself is the definition of the list, not the list object you can walk through.

If you want to inspect each label one by one, you need to ask C# to hand you an actual collection of those labels. Enum.GetValues() is like saying: “Give me all items from this list so I can loop over them.”

Take Quiz

Syntax and Examples

The most common way to loop through enum values in C# is with Enum.GetValues().

public enum Foos
{
    A,
    B,
    C
}

foreach (Foos foo in Enum.GetValues(typeof(Foos)))
{
    Console.WriteLine(foo);
}

Output:

A
B
C

Modern generic form

In newer C# versions, you can use the generic version:

foreach (Foos foo in Enum.GetValues<Foos>())
{
    Console.WriteLine(foo);
}

This is cleaner because you do not need typeof(Foos).

Example with numeric values

public enum Status
{
    Pending = 1,
    Approved = 2,
    Rejected = 3
}

foreach (Status status in Enum.GetValues(typeof(Status)))
{
    Console.WriteLine($"{status} = {(int)status}");
}

Output:

Pending = 1
Approved = 2
Rejected = 3

Why this works

  • Enum.GetValues(...) returns all values defined in the enum
  • foreach loops over that returned collection
  • each item is cast to the enum type

This is the normal and recommended approach for iterating over enum members.

Step by Step Execution

Consider this code:

public enum Foos
{
    A,
    B,
    C
}

foreach (Foos foo in Enum.GetValues(typeof(Foos)))
{
    Console.WriteLine($"Current value: {foo}");
}

Here is what happens step by step:

  1. The enum Foos is defined with three members: A, B, and C.
  2. typeof(Foos) gets the type information for the enum.
  3. Enum.GetValues(typeof(Foos)) creates a collection containing all enum values.
  4. foreach starts reading items from that collection one at a time.
  5. On the first loop, foo is Foos.A.
  6. Console.WriteLine prints Current value: A.
  7. On the second loop, foo is Foos.B.
  8. It prints Current value: B.
  9. On the third loop, foo is Foos.C.
  10. It prints Current value: C.
  11. There are no more items, so the loop ends.

If you want a shorter trace, think of it like this:

Enum.GetValues(typeof(Foos)) -> [A, B, C]
foreach reads A, then B, then C

That is the core idea: convert the enum definition into a collection of values, then iterate over the collection.

Real World Use Cases

Enums are commonly iterated over in practical C# programs.

Building dropdowns or menus

If your app has an enum for user roles or order status, you can loop through the enum values to generate UI options.

public enum UserRole
{
    Guest,
    Member,
    Admin
}

foreach (UserRole role in Enum.GetValues(typeof(UserRole)))
{
    Console.WriteLine($"Option: {role}");
}

Running validation rules for all states

You may want to ensure your code handles every enum value.

public enum OrderStatus
{
    New,
    Paid,
    Shipped,
    Cancelled
}

foreach (OrderStatus status in Enum.GetValues(typeof(OrderStatus)))
{
    Console.WriteLine($"Checking rules for {status}");
}

Testing all enum cases

In unit tests, developers often loop through enum values to verify behavior for every possible option.

Reporting or logging

If a system supports a fixed set of categories, looping through enum values can help generate reports or summaries.

Configuration screens

Enums are often used in application settings, and iterating through them makes it easy to display all supported choices.

Take Quiz

Real Codebase Usage

In real projects, enum iteration usually appears inside helper methods, UI binding code, validation, and tests.

Pattern: create a list of selectable options

var roles = Enum.GetValues(typeof(UserRole))
    .Cast<UserRole>()
    .Select(role => new { Id = (int)role, Name = role.ToString() })
    .ToList();

This pattern is common in MVC apps, APIs, and admin dashboards.

Pattern: guard against unsupported enum values

Even though enums define allowed values, a variable can still hold an undefined numeric value if it was cast manually. Developers often validate with Enum.IsDefined().

int rawValue = 5;
if (Enum.IsDefined(typeof(UserRole), rawValue))
{
    UserRole role = (UserRole)rawValue;
    Console.WriteLine(role);
}
else
{
    Console.WriteLine("Invalid enum value");
}

Pattern: testing all enum cases

foreach (OrderStatus status in Enum.GetValues(typeof(OrderStatus)))
{
    var result = GetStatusMessage(status);
    Console.WriteLine($"{status}: {result}");
}

Pattern: mapping enum values to labels

foreach (UserRole role in Enum.GetValues(typeof(UserRole)))
{
    string label = role switch
    {
        UserRole.Guest => "Guest User",
        UserRole.Member => "Registered Member",
        UserRole.Admin => "Administrator",
        _ => "Unknown"
    };

    Console.WriteLine(label);
}

In production code, enums are often combined with:

  • switch expressions
  • validation
  • LINQ with Cast<T>()
  • API models
  • configuration options

Common Mistakes

Mistake 1: Trying to loop over the enum type directly

Broken code:

foreach (var foo in Foos)
{
    Console.WriteLine(foo);
}

Why it fails:

  • Foos is a type, not a collection

Fix:

foreach (Foos foo in Enum.GetValues(typeof(Foos)))
{
    Console.WriteLine(foo);
}

Mistake 2: Forgetting to cast values to the enum type

Broken code:

foreach (var value in Enum.GetValues(typeof(Foos)))
{
    Console.WriteLine(value);
}

This may still print correctly, but value is not strongly typed as Foos in the clearest possible way.

Better:

foreach (Foos foo in Enum.GetValues(typeof(Foos)))
{
    Console.WriteLine(foo);
}

Mistake 3: Assuming all numeric values are valid enum members

Broken code:

Foos foo = (Foos)99;
Console.WriteLine(foo);

This compiles, but 99 is not defined in the enum.

Avoid this by validating:

if (Enum.IsDefined(typeof(Foos), 99))
{
    Foos foo = (Foos)99;
}

Mistake 4: Confusing enum names with enum values

Enum.GetNames() returns strings:

foreach (string name in Enum.GetNames(typeof(Foos)))
{
    Console.WriteLine(name);
}

This is useful sometimes, but it is not the same as iterating real enum values.

Mistake 5: Ignoring flags enums

If an enum uses [Flags], the defined values may represent bit combinations. Iteration still returns the declared members, not every possible bit combination.

[Flags]
public enum Permissions
{
    None = 0,
    Read = 1,
    Write = 2,
    Execute = 4
}

Looping gives None, Read, Write, and Execute only.

Comparisons

ConceptWhat it returnsBest use
Enum.GetValues(typeof(Foo))Actual enum valuesLoop through enum members
Enum.GetNames(typeof(Foo))Strings with member namesDisplay names or labels
Manual listOnly values you type yourselfSmall custom subsets
switch on enumOne branch for one enum valueHandling logic, not listing all values

Enum.GetValues vs Enum.GetNames

public enum Foos
{
    A,
    B,
    C
}

Using values:

foreach (Foos foo in Enum.GetValues(typeof(Foos)))
{
    Console.WriteLine((int)foo);
}

Using names:

foreach (string name in Enum.GetNames(typeof(Foos)))
{
    Console.WriteLine(name);
}

Choose GetValues when you need the actual enum items for logic. Choose GetNames when you only need text.

Generic vs non-generic form

VersionExampleNotes
Non-genericEnum.GetValues(typeof(Foos))Works broadly and is very common
GenericEnum.GetValues<Foos>()Cleaner and strongly typed

If your project supports the generic version, it is usually easier to read.

Take Quiz

Cheat Sheet

// Define an enum
public enum Foos
{
    A,
    B,
    C
}

// Loop through all values
foreach (Foos foo in Enum.GetValues(typeof(Foos)))
{
    Console.WriteLine(foo);
}

// Generic version
foreach (Foos foo in Enum.GetValues<Foos>())
{
    Console.WriteLine(foo);
}

// Get names only
foreach (string name in Enum.GetNames(typeof(Foos)))
{
    Console.WriteLine(name);
}

// Validate a numeric value
bool isValid = Enum.IsDefined(typeof(Foos), 1);

Key rules

  • An enum type is not directly enumerable
  • Use Enum.GetValues(...) to iterate values
  • Use Enum.GetNames(...) to iterate names as strings
  • Use Enum.IsDefined(...) to validate raw values
  • A cast like (Foos)99 compiles even if 99 is not defined

Remember

  • Foos is a type
  • Enum.GetValues(typeof(Foos)) gives you something you can loop over

FAQ

How do you loop through all enum values in C#?

Use Enum.GetValues():

foreach (Foos foo in Enum.GetValues(typeof(Foos)))
{
    Console.WriteLine(foo);
}

Why can't I use foreach directly on an enum type?

Because an enum is a type definition, not a collection. foreach needs an enumerable object.

What is the difference between Enum.GetValues() and Enum.GetNames()?

  • GetValues() returns enum values
  • GetNames() returns string names

Use GetValues() when you need the actual enum items in logic.

Is Enum.GetValues<T>() better than Enum.GetValues(typeof(T))?

If available in your C#/.NET version, yes. It is cleaner and strongly typed.

Can an enum contain values not explicitly listed?

A variable of an enum type can hold an undefined numeric value if you cast it manually. That is why validation may be needed.

Does looping through a [Flags] enum return every possible combination?

No. It returns the declared enum members, not every possible bitwise combination.

Can I convert enum values to strings while looping?

Yes:

foreach (Foos foo in Enum.GetValues(typeof(Foos)))
{
    Console.WriteLine(foo.ToString());
}
Take Quiz

Mini Project

Description

Create a small C# console program that displays all values of an enum and their numeric equivalents. This demonstrates how enum iteration works in a practical way and mirrors common tasks such as building option lists or debugging allowed states.

Goal

Build a program that loops through an enum and prints each member name and numeric value.

Requirements

  • Define an enum with at least four members
  • Use a foreach loop to iterate through all enum values
  • Print both the enum name and its integer value
  • Keep the program runnable as a simple console app
Take Quiz

Keep learning

Related questions

View more