How to loop through an enum in C#?
How to loop through an enum in C#?
I completed my post-graduation in 2013 in the engineering field. Engineering is the application of science and math to solve problems. Engineers figure out how things work and find practical uses for scientific discoveries. Scientists and inventors often get the credit for innovations that advance the human condition, but it is engineers who are instrumental in making those innovations available to the world. I love pet animals such as dogs, cats, etc.
Ravi Vishwakarma
10-Jun-2024Looping through an enum in C# can be done using the
Enum.GetValuesmethod, which returns an array of the values of the constants in a specified enumeration. This allows you to use aforeachloop to iterate over the enum values.Here’s how you can loop through an enum:
Example Enum Definition
Looping Through the Enum
You can loop through the
DaysOfWeekenum as follows:This will output:
Complete Example
Here is a complete example with the enum definition and the loop:
Additional Considerations
Enum Names: If you need to get the names of the enum values as strings, you can use the
Enum.GetNamesmethod:Enum Parsing: You can parse a string to get the corresponding enum value using
Enum.ParseChecking if Value is Defined: You can check if a value is defined in the enum using
Enum.IsDefinedLooping through an enum is a straightforward task in C# and can be done efficiently with the built-in
Enum.GetValuesandEnum.GetNamesmethods. This approach ensures that your code is both clean and easy to maintain.