tags:

views:

215

answers:

1
+7  Q: 

Iterate over enum?

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.

+5  A: 

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
You can also not be lazy and use GameObjectType in the second example instead of var :)
Charles Boyung
@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
@Jon: 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