How to loop through an enum in C#? |
In C#, an enum (short for "enumeration") is a set of named integer constants. Enumerations are used to define a set of related named constants, which can be useful for things like representing states, options, or settings.
To loop through an enum in C#, you can use the Enum.GetValues
method, which returns an array of the values of the enum. Here's an example:
In this example, we have defined an enum called Colors
with three values: Red
, Green
, and Blue
. To loop through the values of this enum, we use a foreach
loop to iterate over the array returned by the Enum.GetValues
method. We pass the typeof(Colors)
argument to the method to specify the type of the enum whose values we want to retrieve.
Inside the loop, we simply print each value of the enum to the console using Console.WriteLine
.
Note that the Enum.GetValues
method returns an Array
object, which means you need to cast each element to the correct enum type before you can use it. In this example, we are using the Colors
enum type, so we cast each element to that type in the loop header.
You can also use the Enum.GetNames
method to retrieve an array of the names of the enum values. Here's an example:
This loop will print the names of the enum values ("Red"
, "Green"
, and "Blue"
) instead of their integer values.