Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to iterate through each choice in an enum? [duplicate]

Possible Duplicate:
How to enumerate an enum?

So I have a bit of code like this:

enum Decision
{
  DecisionA,
  DecisionB,
  ...
}

public void DoStuff(Decision d)
{
  switch(d)
  {
    case Decision.DecisionA:
    ....
    ...
  }
}

Basically DoStuff, will do the same thing no matter what the decision, but the decision is used to make what it does more optimal(faster or whatever).

Now, I'd like to implement unit testing for DoStuff. It's fairly easy to test that all the Decisions work properly by having an array like new Decision[]{DecisionA, DecisionB, ...}; However, if I add a decision, I then have to go back and manually add it to the unit test.

Is it possible to just access all of the possible options specified by an enum? For instance, something like this:

foreach(var d in Decision.Options)
{
  //d will be DecisionA, and then DecisionB, etc etc
}
like image 694
Earlz Avatar asked Dec 09 '22 19:12

Earlz


1 Answers

You can use Enum.GetValues, but personally I'm not a huge fan of that. You'd need to cast (e.g. by specifying the iteration variable type), and provide the type via typeof:

foreach (Decision decision in Enum.GetValues(typeof(Decision)))
{
}

I prefer the option I made available in Unconstrained Melody - a little library providing extension methods on enums and delegates:

foreach (var decision in Enums.GetValues<Decision>())
{
}

This is:

  • Type-safe in return type (it returns an IList<T>)
  • Type-safe in type argument (the type has to be an enum)
  • More efficient as it reuses the same read-only list for all calls

Of course it does mean using an extra library... it may well not be worth it for you for just a single call, but if you're doing a lot of things with enums, you may find the other features useful.

like image 161
Jon Skeet Avatar answered Jan 19 '23 01:01

Jon Skeet