An
enum in .NET is a structure that maps a set of values (fields) to a basic type (the default is int). Enums are kind of like
integers , but you can't rely on their values to always be sequential or ascending. To get all values of an enum, we can use the
Enum.GetValues static method.
class EnumLoop {
enum MyEnum
{
High = 10,
Medium = 5,
Low = 1
}
public static void Main() {
foreach (MyEnum enumValue in Enum.GetValues(typeof(MyEnum)))
{
Console.WriteLine(enumValue);
}
}
}
output
Medium
High
Low
The following C# code snippet loops through all values of an enum and prints them on the console.
class EnumLoop {
enum MyEnum
{
High = 10,
Medium = 5,
Low = 1
}
public static void Main() {
foreach (int i in Enum.GetValues(typeof(MyEnum)))
{
Console.WriteLine($" {i}" );
}
}
}
output
1
5
10
Enum.GetValues(Type)
Enum.GetValues(Type) method retrieves an array of the values of the constants in a specified
enumeration .
public static Array GetValues (Type enumType);
If multiple members have the same value, the returned array includes
duplicate values .