Nov 28, 2021

Enumerating an enum in C# | Interview Question

To enumerate an enum type you can use Enum.GetValues method as follows

enum Animals
{
    Cat,
    Dog,
    Mouse,
    Monkey
}
void Main()
{
    var allAnimals = Enum.GetValues(typeof(Animals));
    Console.WriteLine(allAnimals.Length);
    foreach(var animal in allAnimals)
    {
        Console.WriteLine(animal);
    }
}

Enum.GetValues documentation:

https://docs.microsoft.com/en-us/dotnet/api/system.enum.getvalues?view=net-6.0