C#: How Can We Enumerate An Enum?

Question

How can I enumerate an enum data type in C#?

Say I have this:

    enum PumpkinVariety
    {
        BabyBear,
        FunnyFace,
        HarvestMoon,
        GhostRider,
        BigMax
    }

How can I list this dynamically in any useful way?

Short Answer

If you have a plain vanilla enum, and you don’t have any funky stuff there such as duplicated values, it’s as easy as this:

foreach (PumpkinVariety pv in Enum.GetValues(typeof(PumpkinVariety)))
{
    // do something here
}

If you do have funky stuff going on, that’s another matter…

Continue reading “C#: How Can We Enumerate An Enum?”