Iterate through Enums
If I want to make an action iterate through an enum everytime it's taken, obviously I would just use
object++;
but what do I except when I reach the max value and want it to return back to the min value? And if a simple increment doesn't work how would I loop through the enum as such?12 Replies
iterate through an enum in what way?
You can use this https://learn.microsoft.com/en-us/dotnet/api/system.enum.getvalues?view=net-9.0
And then iterate them that way.
or if they follow the default pattern of 0, 1, 2, 3 .. you can just do a for-loop and cast the integer to the specified enum
I would essentially want to go 0, 1, 2, 3, 0, 1....
How many times?
You can just use
index = i % totalEnumCount
% is the remainder
https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/operators/arithmetic-operators#remainder-operator-The number of times is irrelevant. The enum would only change when an action is taken. But I could do something like this?
I picked 4 because that's the length of my enum.
why + 1?
Cuz I want the next enum. And the modulo would keep the value within the bounds of the enum?
Can I apply further calculations after using the increment operator?
randomEnum++ % 4
no
% takes precedence
So I'd have to calculate the index, then apply the modulo. In seperate equations.
Why? Just
x = (x + 1) % Length
what if enum is like this
i dont think increment would work with that enum
Buddy
You can use this https://learn.microsoft.com/en-us/dotnet/api/system.enum.getvalues?view=net-9.0
And then iterate them that way.
Quoted by
<@203166497198047232> from #Iterate through Enums (click here)
React with ❌ to remove this embed.
But yes, you are right. It wouldn't work that way. But you can access their values and do it against the index of the values and then cast that to the enum