1

I would like to iterate over the values of a enum property, the following method works but it feels long winded. Are there any methods built in to the .net libraries or some for loop I'm missing?

[Flags]
public enum Animals
{
    Dog     = 1,
    Cat     = 2,
    Sheep   = 4,
    Cow     = 8,
    Goat    = 16
}

var myAnimals = Animals.Dog | Animals.Sheep | Animals.Goat;

foreach (Animals animal in Enum.GetValues(typeof(Animals)))
{
    if (myAnimals.HasFlag(animal))
    {
        Console.WriteLine($"You have a {animal}");
    }
}

Syntactically this would be perfect.

foreach (Animals animal in myAnimals)
{
    Console.WriteLine($"You have a {animal}");
}

Sure I could create a utility method, but if I am missing a builtin method I would prefer to use that.

Anth12
  • 1,869
  • 2
  • 20
  • 39
  • Duplicate question: http://stackoverflow.com/questions/972307/can-you-loop-through-all-enum-values – Fabiano Apr 13 '17 at 10:19
  • @Fabiano that is a different question as the Q asks for all possible values of an enum. The link DavidG provided however is the same, I guess there is no better way of doing it. – Anth12 Apr 13 '17 at 10:22

0 Answers0