enum
programming
enumeration
coding
software-development

How can I enumerate an enum?

Master System Design with Codemia

Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.

Introduction

Enumerating an enum means iterating through every defined member in a controlled, predictable way. This is useful for UI option lists, validation, and serialization logic because it keeps the allowed values in one place instead of duplicating them across the codebase.

Why Enumerating the Enum Is Better Than Hardcoding Lists

A common anti-pattern is storing enum members in one place and maintaining a separate string array or dropdown list somewhere else. That works until someone adds a new enum member and forgets to update the manual list.

Enumerating the enum directly avoids that drift. It also makes it easier to:

  1. build option lists from the source of truth
  2. validate external input against legal values
  3. attach labels or metadata to each member
  4. keep tests aligned with the actual type

Enumerating Enums in C#

In C#, Enum.GetValues and Enum.GetNames are the standard APIs. Enum.TryParse complements them when you need to convert user input back into the enum safely.

csharp
1using System;
2using System.Linq;
3
4public enum InvoiceStatus
5{
6    Draft = 1,
7    Sent = 2,
8    Paid = 3,
9    Overdue = 4,
10    Cancelled = 5
11}
12
13public static class Program
14{
15    public static void Main()
16    {
17        foreach (InvoiceStatus status in Enum.GetValues(typeof(InvoiceStatus)))
18        {
19            Console.WriteLine($"{status} => {(int)status}");
20        }
21
22        bool ok = Enum.TryParse<InvoiceStatus>("Paid", ignoreCase: true, out var parsed);
23        Console.WriteLine(ok ? parsed : "invalid");
24    }
25}

This is a strong default when you need a list of members or safe parsing from strings.

Enumerating Enums in Python

Python enums are iterable by design, which makes option generation simple.

python
1from enum import Enum
2
3class AccessLevel(Enum):
4    READ = "read"
5    WRITE = "write"
6    ADMIN = "admin"
7
8for level in AccessLevel:
9    print(level.name, level.value)
10
11options = [{"key": level.name, "value": level.value} for level in AccessLevel]
12print(options)

If you also need parsing, make it explicit rather than relying on a fragile string lookup scattered through the code.

python
1def parse_level(raw: str):
2    normalized = raw.strip().lower()
3    for level in AccessLevel:
4        if level.value == normalized:
5            return level
6    return None

Enumerating Enums in Java

Java enums provide a generated values() method, which is the normal way to iterate over them.

java
1enum Priority {
2    LOW("Low"),
3    MEDIUM("Medium"),
4    HIGH("High");
5
6    private final String label;
7
8    Priority(String label) {
9        this.label = label;
10    }
11
12    public String label() {
13        return label;
14    }
15}
16
17public class Demo {
18    public static void main(String[] args) {
19        for (Priority priority : Priority.values()) {
20            System.out.println(priority.name() + " -> " + priority.label());
21        }
22    }
23}

This pattern works well when the enum also carries display labels or other metadata.

Separate Labels From Identifiers

One subtle design mistake is using enum member names directly as user-facing text or wire-format values forever. Internal identifiers, display labels, and external serialized values often have different stability requirements.

A safer pattern is:

  1. keep the enum member as the internal type-safe identifier
  2. attach a label or explicit value for presentation or serialization
  3. parse input through a dedicated helper

That keeps refactoring safer and avoids surprising downstream breakage.

Treat Enumeration Order Carefully

Many languages preserve declaration order during iteration, but you should still decide whether that order is part of your contract. If UI order matters, it may be better to sort explicitly or attach an ordering field instead of assuming enum declaration order will always reflect business priority.

This is especially important when different teams edit the enum over time.

Common Pitfalls

The biggest mistake is maintaining a manual list of allowed values next to the enum and letting the two drift apart. Another is exposing raw enum names directly to users when display labels should be decoupled. Developers also forget to update parsing and serialization tests when a new enum member is added.

Summary

  • Enumerate the enum directly instead of maintaining duplicate manual lists.
  • Use native APIs such as Enum.GetValues, direct enum iteration, and values().
  • Keep parsing explicit and safe rather than relying on exceptions or scattered string checks.
  • Separate internal enum identifiers from display labels and wire values.
  • Add tests so new enum members are reflected automatically in validation and UI logic.

Course illustration
Course illustration

All Rights Reserved.