Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
How to loop through all values of an enum in C#?
In C#, you can loop through all values of an enum using the Enum.GetValues() method. This method returns an array containing all the values defined in the enum, which you can then iterate over using a foreach loop.
Syntax
Following is the syntax for looping through enum values −
foreach (EnumType value in Enum.GetValues(typeof(EnumType))) {
// Process each enum value
}
You can also use the generic version for type safety −
foreach (EnumType value in Enum.GetValues<EnumType>()) {
// Process each enum value (C# 5.0+)
}
Using Enum.GetValues() with foreach Loop
First, define an enum and then use Enum.GetValues(typeof(EnumName)) inside a foreach loop to iterate through all its values −
Example
using System;
public class EnumExample {
public enum Grade { A, B, C, D, E, F };
public static void Main() {
Console.WriteLine("All grades:");
foreach (Grade g in Enum.GetValues(typeof(Grade))) {
Console.WriteLine(g);
}
}
}
The output of the above code is −
All grades: A B C D E F
Using Enum.GetValues() with Numeric Enums
When working with enums that have explicit numeric values, Enum.GetValues() still returns all defined values −
Example
using System;
public class NumericEnumExample {
public enum HttpStatusCode {
OK = 200,
NotFound = 404,
InternalServerError = 500
};
public static void Main() {
Console.WriteLine("HTTP Status Codes:");
foreach (HttpStatusCode status in Enum.GetValues(typeof(HttpStatusCode))) {
Console.WriteLine($"{status} = {(int)status}");
}
}
}
The output of the above code is −
HTTP Status Codes: OK = 200 NotFound = 404 InternalServerError = 500
Alternative Approaches
Besides Enum.GetValues(), you can also use Enum.GetNames() to get string representations of enum values −
Example
using System;
public class EnumNamesExample {
public enum Priority { Low, Medium, High, Critical };
public static void Main() {
Console.WriteLine("Using Enum.GetNames():");
foreach (string name in Enum.GetNames(typeof(Priority))) {
Console.WriteLine(name);
}
Console.WriteLine("\nUsing Enum.GetValues() with names:");
foreach (Priority p in Enum.GetValues(typeof(Priority))) {
Console.WriteLine($"Name: {p}, Value: {(int)p}");
}
}
}
The output of the above code is −
Using Enum.GetNames(): Low Medium High Critical Using Enum.GetValues() with names: Name: Low, Value: 0 Name: Medium, Value: 1 Name: High, Value: 2 Name: Critical, Value: 3
Conclusion
The Enum.GetValues() method is the most efficient way to loop through all values of an enum in C#. It works with both simple and numeric enums, returning an array that can be easily iterated using a foreach loop to access each enum value.
