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:
ABC
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.”
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:
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:
- The enum
Foosis defined with three members:A,B, andC. typeof(Foos)gets the type information for the enum.Enum.GetValues(typeof(Foos))creates a collection containing all enum values.foreachstarts reading items from that collection one at a time.- On the first loop,
fooisFoos.A. Console.WriteLineprintsCurrent value: A.- On the second loop,
fooisFoos.B. - It prints
Current value: B.
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.
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
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:
Foosis 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
Comparisons
| Concept | What it returns | Best use |
|---|---|---|
Enum.GetValues(typeof(Foo)) | Actual enum values | Loop through enum members |
Enum.GetNames(typeof(Foo)) | Strings with member names | Display names or labels |
| Manual list | Only values you type yourself | Small custom subsets |
switch on enum | One branch for one enum value | Handling logic, not listing all values |
Enum.GetValues vs Enum.GetNames
public enum Foos
{
A,
B,
C
}
Using values:
(Foos foo Enum.GetValues((Foos)))
{
Console.WriteLine(()foo);
}
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)99compiles even if99is not defined
Remember
Foosis a typeEnum.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 valuesGetNames()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 enum return every possible combination?
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
foreachloop to iterate through all enum values - Print both the enum name and its integer value
- Keep the program runnable as a simple console app
Keep learning
Related questions
AddTransient vs AddScoped vs AddSingleton in ASP.NET Core Dependency Injection
Learn the differences between AddTransient, AddScoped, and AddSingleton in ASP.NET Core DI with examples and practical usage.
C# Type Checking Explained: typeof vs GetType() vs is
Learn when to use typeof, GetType(), and is in C#. Understand exact type checks, inheritance, and safe type testing clearly.
C# Version Numbers Explained: C# vs .NET Framework and Why “C# 3.5” Is Incorrect
Learn the correct C# version numbers, how they map to .NET releases, and why terms like C# 3.5 are inaccurate and confusing.