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.
Enumeration (enum) in Java is a datatype which stores a set of constant values. You can use enumerations to store fixed values such as days in a week, months in a year etc. You can iterate the contents of an enumeration using for loop, using forEach loop and, using java.
Iterating over an enum in C# Enums are kind of like integers , but you can't rely on their values to always be sequential or ascending. To get all values of an enum, we can use the Enum. GetValues static method. The following C# code snippet loops through all values of an enum and prints them on the console.
C++ Enumeration Iteration over an enumThere is no built-in to iterate over enumeration.
Use the enumeration[member_name] to access a member by its name and enumeration(member_value) to access a member by its value. Enumerations are iterable. Enumeration members are hashable.
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...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With