Question

How to Enumerate an Enum in C#

csharp.netloopsenumsenumeration

Question

In C#, how can you iterate over all values of an enum?

For example, the following code does not compile:

public enum Suit
{
    Spades,
    Hearts,
    Clubs,
    Diamonds
}

public void EnumerateAllSuitsDemoMethod()
{
    foreach (Suit suit in Suit)
    {
        DoSomething(suit);
    }
}

This produces the compile-time error:

'Suit' is a 'type' but is used like a 'variable'

The error occurs on the second Suit in the foreach statement. What is the correct way to enumerate all values of a C# enum?

Short Answer

By the end of this page, you will understand how to loop through every value in a C# enum, why an enum type cannot be used directly in a foreach, and how to use Enum.GetValues(...) correctly in beginner-friendly and real-world code.

Concept

In C#, an enum is a type that represents a fixed set of named constants. For example, Suit defines four possible values: Spades, Hearts, Clubs, and Diamonds.

The key idea is this:

  • Suit is a type definition
  • Suit.Spades is an enum value
  • foreach needs a collection of values to iterate over

That is why this does not work:

foreach (Suit suit in Suit)

Here, the second Suit is just the enum type itself, not a list or sequence. foreach cannot loop over a type.

To enumerate all values of an enum, you need to ask .NET for the values defined in that enum. The standard way is:

Enum.GetValues(typeof(Suit))

This returns all defined values for the enum, which you can then loop through.

This matters in real programming because enums are commonly used for:

  • menu choices
  • status values
  • configuration options
  • user roles
  • API states
  • game logic

Being able to enumerate enum values is useful when you want to:

  • display all available options
  • validate input against allowed values
  • build dropdown lists
  • run logic for every possible enum member

Mental Model

Think of an enum like a category label printed on a box, and the enum values as the items inside the box.

  • Suit = the name on the box
  • Spades, Hearts, Clubs, Diamonds = the items inside

You cannot loop over the box label itself. You need to open the box and get the items out first.

Enum.GetValues(typeof(Suit)) is the tool that opens the box and gives you all the values to iterate over.

Take Quiz

Syntax and Examples

Basic syntax

In C#, use Enum.GetValues to get all values from an enum.

foreach (Suit suit in Enum.GetValues(typeof(Suit)))
{
    DoSomething(suit);
}

Complete example

using System;

public enum Suit
{
    Spades,
    Hearts,
    Clubs,
    Diamonds
}

public class Program
{
    public static void Main()
    {
        foreach (Suit suit in Enum.GetValues(typeof(Suit)))
        {
            Console.WriteLine(suit);
        }
    }
}

Output:

Spades
Hearts
Clubs
Diamonds

Generic version in modern C#

If your C# version supports it, you can use the generic overload:

foreach (Suit suit in Enum.GetValues<Suit>())
{
    Console.WriteLine(suit);
}

This version is cleaner because you do not need typeof(Suit) or casting.

Getting enum names instead of values

If you only want the names as strings:

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

Use this when you need text labels rather than enum values themselves.

Step by Step Execution

Consider this code:

using System;

public enum Suit
{
    Spades,
    Hearts,
    Clubs,
    Diamonds
}

public class Program
{
    public static void Main()
    {
        foreach (Suit suit in Enum.GetValues(typeof(Suit)))
        {
            Console.WriteLine($"Current suit: {suit}");
        }
    }
}

Here is what happens step by step:

  1. The enum Suit is defined with four members.
  2. Enum.GetValues(typeof(Suit)) asks .NET for all values declared in the Suit enum.
  3. .NET returns a collection containing:
    • Suit.Spades
    • Suit.Hearts
    • Suit.Clubs
    • Suit.Diamonds
  4. The foreach loop starts with the first value.
  5. The variable suit becomes Suit.Spades.
  6. Console.WriteLine prints Current suit: Spades.
  7. The loop repeats for Hearts, then Clubs, then Diamonds.
  8. After the last value, the loop ends.

You can think of it like this:

// Conceptually similar to:
Suit[] suits = { Suit.Spades, Suit.Hearts, Suit.Clubs, Suit.Diamonds };

foreach (Suit suit in suits)
{
    Console.WriteLine($"Current suit: {suit}");
}

Enum.GetValues creates that list for you automatically based on the enum definition.

Real World Use Cases

Building a dropdown or menu

Enums are often used for a fixed list of options. For example:

  • payment status
  • shipping method
  • user role
  • order state

You can enumerate the enum to display all choices.

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

foreach (OrderStatus status in Enum.GetValues(typeof(OrderStatus)))
{
    Console.WriteLine(status);
}

Validating input

You may want to compare input against all valid enum values.

Running logic for every case

In games or simulations, you might apply rules for every possible state or category.

Generating reports

If an enum represents categories, you can loop through all categories and summarize data for each one.

Seeding configuration or defaults

A real application may create default records for every enum member, such as permissions or settings.

Take Quiz

Real Codebase Usage

In real projects, developers usually do more than just print enum values. They combine enum enumeration with common patterns.

1. Creating UI options

var suitOptions = Enum.GetValues(typeof(Suit))
    .Cast<Suit>()
    .Select(s => s.ToString())
    .ToList();

This is useful when building select lists or API response options.

2. Validation

public bool IsValidSuit(Suit suit)
{
    return Enum.IsDefined(typeof(Suit), suit);
}

This helps when values may come from external input.

3. Guard clauses

public void ProcessSuit(Suit suit)
{
    if (!Enum.IsDefined(typeof(Suit), suit))
    {
        throw new ArgumentException("Invalid suit value.");
    }

    Console.WriteLine($"Processing {suit}");
}

4. Filtering enum values

Sometimes not every enum value should be shown.

foreach (Suit suit in Enum.GetValues(typeof(Suit)))
{
    if (suit == Suit.Clubs)
        continue;

    Console.WriteLine(suit);
}

5. Mapping enum values to display text

public static string GetSuitLabel(Suit suit)
{
    return suit switch
    {
        Suit.Spades => "Spades ♠",
        Suit.Hearts => "Hearts ♥",
        Suit.Clubs => "Clubs ♣",
        Suit.Diamonds => "Diamonds ♦",
        _ => suit.ToString()
    };
}

Then enumerate and display labels.

foreach (Suit suit in Enum.GetValues(typeof(Suit)))
{
    Console.WriteLine(GetSuitLabel(suit));
}

Common Mistakes

Mistake 1: Trying to loop over the enum type directly

Broken code:

foreach (Suit suit in Suit)
{
    Console.WriteLine(suit);
}

Why it fails:

  • Suit is a type, not a collection.
  • foreach requires something enumerable.

Fix:

foreach (Suit suit in Enum.GetValues(typeof(Suit)))
{
    Console.WriteLine(suit);
}

Mistake 2: Forgetting to cast when needed

Enum.GetValues(typeof(Suit)) returns an array-like collection of enum values, but older syntax may require casting when using LINQ.

var suits = Enum.GetValues(typeof(Suit)).Cast<Suit>();

Mistake 3: Confusing names with values

Enum.GetNames returns strings, not enum values.

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

If you need actual Suit values, use Enum.GetValues instead.

Mistake 4: Assuming enum values are always consecutive

Enums often default to 0, 1, 2, 3, but developers can assign custom values.

public enum Suit
{
    Spades = 10,
    Hearts = 20,
    Clubs = 30,
    Diamonds = 40
}

Enum.GetValues still works correctly, but you should not assume values are sequential unless you defined them that way.

Mistake 5: Ignoring invalid enum values

A variable of enum type can still hold a numeric value not explicitly defined in the enum.

Suit suit = (Suit)999;

Use Enum.IsDefined if you need to ensure the value is one of the declared members.

Comparisons

ApproachWhat it returnsBest useExample
Enum.GetValues(typeof(Suit))All enum valuesLooping through enum membersforeach (Suit suit in Enum.GetValues(typeof(Suit)))
Enum.GetValues<Suit>()All enum valuesCleaner modern syntaxforeach (Suit suit in Enum.GetValues<Suit>())
Enum.GetNames(typeof(Suit))All enum names as stringsUI labels, text outputforeach (string name in Enum.GetNames(typeof(Suit)))
Direct enum type SuitJust the type itselfDeclaring variables, parameters, propertiesSuit suit = Suit.Spades;

Enum values vs enum names

ItemTypeExample
Enum valueSuitSuit.Hearts
Enum namestring"Hearts"
Underlying numeric valueusually int(int)Suit.Hearts

Enum.GetValues vs hardcoded array

OptionProsCons
Enum.GetValuesAlways stays in sync with the enumSlightly more verbose
Hardcoded arrayCan choose custom order or subsetMust be updated manually

Example hardcoded array:

Suit[] redSuits = { Suit.Hearts, Suit.Diamonds };
Take Quiz

Cheat Sheet

Enumerate all enum values

foreach (Suit suit in Enum.GetValues(typeof(Suit)))
{
    Console.WriteLine(suit);
}

Modern generic syntax

foreach (Suit suit in Enum.GetValues<Suit>())
{
    Console.WriteLine(suit);
}

Get enum names as strings

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

Get underlying numeric value

int value = (int)Suit.Spades;

Validate enum value

bool isValid = Enum.IsDefined(typeof(Suit), suit);

Key rule

  • An enum type like Suit is not a collection.
  • Use Enum.GetValues(...) when you want to loop through all members.

Common pattern

var suits = Enum.GetValues(typeof(Suit));
foreach (Suit suit in suits)
{
    // use suit
}

Edge case

Enum variables can contain undefined numeric values:

Suit suit = (Suit)999;

Use Enum.IsDefined if needed.

FAQ

How do you loop through enum values in C#?

Use Enum.GetValues(typeof(YourEnum)) or Enum.GetValues<YourEnum>() and iterate with foreach.

Why can't I use the enum type directly in foreach?

Because the enum type is only a type definition, not a collection of values. foreach needs something enumerable.

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

Enum.GetValues returns actual enum values. Enum.GetNames returns their names as strings.

Does Enum.GetValues return values in declaration order?

It returns the enum values defined for that type. In common cases this matches the declared members, but the important point is that it returns the defined enum values rather than the type itself.

Can an enum contain values not explicitly declared?

Yes. Because enums are numeric underneath, you can cast a number to an enum even if it is not declared. Use Enum.IsDefined to validate.

Is there a generic version of Enum.GetValues?

Yes. In modern C#, you can use Enum.GetValues<YourEnum>(), which is cleaner and type-safe.

Should I use enum names or enum values for UI?

Use enum values for logic and names or mapped labels for display. Often developers convert enum values into user-friendly text before showing them.

Take Quiz

Mini Project

Description

Create a small console program that lists all possible order states for an application and prints a user-friendly message for each one. This demonstrates how to enumerate an enum, process every enum member, and map values to display text.

Goal

Build a C# console app that loops through every enum value and prints a readable description for each state.

Requirements

  1. Create an enum named OrderStatus with at least four values.
  2. Use Enum.GetValues or Enum.GetValues<T>() to iterate through all enum members.
  3. Print each enum value and a friendly description.
  4. Use a switch expression or switch statement to generate the description.
Take Quiz

Keep learning

Related questions

View more