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:
Suitis a type definitionSuit.Spadesis an enum valueforeachneeds 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.
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 boxSpades,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.
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.
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:
- The enum
Suitis defined with four members. Enum.GetValues(typeof(Suit))asks .NET for all values declared in theSuitenum.- .NET returns a collection containing:
Suit.SpadesSuit.HeartsSuit.ClubsSuit.Diamonds
- The
foreachloop starts with the first value. - The variable
suitbecomes .
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.
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.
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:
Suitis a type, not a collection.foreachrequires 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);
}
Comparisons
| Approach | What it returns | Best use | Example |
|---|---|---|---|
Enum.GetValues(typeof(Suit)) | All enum values | Looping through enum members | foreach (Suit suit in Enum.GetValues(typeof(Suit))) |
Enum.GetValues<Suit>() | All enum values | Cleaner modern syntax | foreach (Suit suit in Enum.GetValues<Suit>()) |
Enum.GetNames(typeof(Suit)) | All enum names as strings | UI labels, text output | foreach (string name in Enum.GetNames(typeof(Suit))) |
Direct enum type Suit | Just the type itself | Declaring variables, parameters, properties |
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
Suitis not a collection. - Use
Enum.GetValues(...)when you want to loop through all members.
Common pattern
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 , which is cleaner and type-safe.
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
- Create an enum named
OrderStatuswith at least four values. - Use
Enum.GetValuesorEnum.GetValues<T>()to iterate through all enum members. - Print each enum value and a friendly description.
- Use a
switchexpression orswitchstatement to generate the description.
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.