24

I'm trying to iterate over an enum, and call a method using each of its values as a parameter. There has to be a better way to do it than what I have now:

foreach (string gameObjectType in Enum.GetNames(typeof(GameObjectType)))
{
     GameObjectType kind = (GameObjectType) Enum.Parse(typeof (GameObjectType), gameObjectType);
     IDictionary<string, string> gameObjectData = PersistentUtils.LoadGameObject(kind, persistentState);
}

//...

public static IDictionary<string, string> LoadGameObject(GameObjectType gameObjectType, IPersistentState persistentState) { /* ... */ }

Getting the enum names as strings, then parsing them back to enums, feels hideous.

John Saunders
  • 160,644
  • 26
  • 247
  • 397
Nick Heiner
  • 119,074
  • 188
  • 476
  • 699
  • possible duplicate of [C# Iterating through an enum? (Indexing a System.Array)](http://stackoverflow.com/questions/482729/c-sharp-iterating-through-an-enum-indexing-a-system-array) – Ian Goldby Jul 29 '15 at 08:45

2 Answers2

35

Well, you can use Enum.GetValues:

foreach (GameObjectType type in Enum.GetValues(typeof(GameObjectType))
{
    ...
}

It's not strongly typed though - and IIRC it's pretty slow. An alternative is to use my UnconstrainedMelody project:

// Note that type will be inferred as GameObjectType :)
foreach (var type in Enums.GetValues<GameObjectType>())
{
    ...
}

UnconstrainedMelody is nice if you're doing a lot of work with enums, but it might be overkill for a single usage...

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • You can also not be lazy and use GameObjectType in the second example instead of var :) – Charles Boyung Apr 13 '10 at 20:03
  • 1
    @Charles: I was doing that to demonstrate that it really was strongly typed... in the first version that would end up with it being `object`. – Jon Skeet Apr 13 '10 at 20:10
  • 2
    All right, I suppose I'll let it go this time. Just way too many C# examples nowadays that lazily use var for everything. – Charles Boyung Apr 13 '10 at 20:12
  • 1
    @CharlesBoyung why is it laziness? Removing visual clutter from the code is a Good Thing. This avoids nonsense like `MyLongAndDescriptiveClassName myLongAndDescriptiveClassNameInstance = new MyLongAndDescriptiveClassName(... )`. (maybe an argument for another place) – CJBrew Nov 04 '16 at 12:21
1

Just in case anyone else is crazy enough to want to do wants to do this in C++/CLI, here's a port which works:

using namespace System;

enum class GameObjectType
{
    num1 = 1,
    num2 = 2,
};

Array^ objectTypes = Enum::GetValues(GameObjectType::typeid);
for each( GameObjectType^ objectType in objectTypes)
{
    // Do something
}
Jon Cage
  • 36,366
  • 38
  • 137
  • 215