by Sai gowtham

How to enumerate an enum in c#

We can use the enum.GetNames() method to enumerate through a enum in c#.

public enum Fruits
{
    Orange,
    Grapes,
    Apple
}

public void PrintAllFruits()
{
    foreach (string fruit in Enum.GetNames(typeof(Fruits)))
    {
        System.Console.WriteLine(fruit);
    }
}

In the above example, we are iterating through a Fruits enum and printing each enum in the console.

Iterating through enum values

If you want enum values instead of names you need to use enum.GetValues() method.

public void PrintAllFruits()
{
    foreach (string fruit in Enum.GetValues(typeof(Fruits)))
    {
        System.Console.WriteLine(fruit);
    }
}

Top Udemy Courses

JavaScript - The Complete Guide 2020 (Beginner + Advanced)
JavaScript - The Complete Guide 2020 (Beginner + Advanced)
45,614 students enrolled
52 hours of video content
View Course
React - The Complete Guide (incl Hooks, React Router, Redux)
React - The Complete Guide (incl Hooks, React Router, Redux)
284,472 students enrolled
40 hours of video content
View Course
Vue JS 2 - The Complete Guide (incl. Vue Router & Vuex)
Vue JS 2 - The Complete Guide (incl. Vue Router & Vuex)
130,921 students enrolled
21 hours of video content
View Course